【问题标题】:Should super().__str__() in Brython return something different?Brython 中的 super().__str__() 是否应该返回不同的东西?
【发布时间】:2020-04-23 13:41:52
【问题描述】:

我在使用 Brython 和使用 str 方法的继承时遇到了一个奇怪的情况。这是我使用Brython console 进行的测试:

>>> class A(object):
...     def __str__(self):
...         return "A __str__ output."
... 
>>> class B(A):
...     def __str__(self):
...         return super().__str__() + " (from B)"
... 
>>> x = A()
>>> x
<__main__.A object>
>>> y = B()
>>> y
<__main__.B object>
>>> str(y)
"<super: <class 'B'>, <B object>> (from B)"

我期待最后一行返回:

"A __str__ output. (from B)"

我在这里做错了吗?

【问题讨论】:

标签: python brython


【解决方案1】:

相同的代码在 CPython 中运行良好,因此可能是 Brython 错误。

Python 3.7.6 (default, Dec 30 2019, 19:38:26)
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
...     def __str__(self):
...         return "A __str__ output."
...
>>> class B(A):
...     def __str__(self):
...         return super().__str__() + " (from B)"
...
>>> x = A()
>>> x
<__main__.A object at 0x1048de590>
>>> y = B()
>>> y
<__main__.B object at 0x1048de790>
>>> str(y)
'A __str__ output. (from B)'
>>>

【讨论】:

【解决方案2】:

这不一定是错误,也可能是特定于实现的行为。 Pyhton 中 super() 函数的行为也发生了变化,因此您必须确保使用正确的形式,并针对兼容的实现进行测试。

您的情况是 您正在打印由super()返回的代理对象的字符串表示,而不是在实际父对象上调用__str__.

更多信息请看这里:https://docs.python.org/3/library/functions.html#super

【讨论】:

  • 不,super() 是正确的方法,但您可能必须添加参数基类和/或实例,例如super(A).__str__()(查看文档,我不确定)。
  • 我不认为这是特定于实现的。无法调用上游 __str__ 方法将破坏创建 super 的用例。
  • super 添加显式参数并没有帮助,因此这不仅仅是魔术参数提供行为被破坏的问题。
  • 如果您尝试使用 super 调用另一个方法,例如 def my_str(self): return self.__str__() 并尝试调用 super().my_str()super(A).my_str(),会发生什么情况?这行得通吗?
  • 如果它与其他方法一起使用,但不仅仅是__str__,它确实闻起来像一个错误。解决方法应该是微不足道的,但对于所有后代来说,至少尝试报告它。
猜你喜欢
  • 2020-10-14
  • 2010-10-22
  • 2019-05-22
  • 2020-09-04
  • 1970-01-01
  • 2013-08-23
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
相关资源
最近更新 更多