我尝试将某些东西从 python2 移植到 python3,但遇到了有关以下类的错误:
class Bound(tuple):
# some methods skipped…
def __new__(cls, value, is_closed):
if value is NegativeInfinity or value is PositiveInfinity:
is_closed = False
return tuple.__new__(cls, (value, is_closed))
def __init__(self, value, is_closed):
"""
See __new__
"""
super(Bound, self).__init__((value, is_closed))
尝试初始化时,它会失败并显示 object.__init__() takes no parameters
。看起来 super(Bound, self).__init__(…)
访问了 object
的 __init__
方法,这似乎是错误的——不是 super
只是在对象处前进 __mro__
?
为了缩小范围,我编写了以下结构:
class T(tuple):
def __new__(cls, arg):
return super(T, cls).__new__(cls, arg)
def __init__(self, arg):
return super(T, self).__init__(arg)
在这个例子中,我得到了同样的错误:T([])
告诉我 object.__init__() takes no parameters
尽管如此。
由于 T.__mro__
是 (__main__.T, tuple, object)
,这本质上是令人困惑的。在没有明确声明类型和实例的情况下使用 super()
时会发生完全相同的情况。
出了什么问题?
最佳答案
It appears that
super(Bound, self).__init__(…)
accesses the__init__
method ofobject
, which seems wrong – doesn'tsuper
just advance at the objects__mro__
?
object.__init__
是 MRO 中的下一个 __init__
,因为 tuple
没有自己的__init__
。
在 Python 2 上,这会给您一个(默认情况下被抑制)警告。在 Python 3 上,这是一个错误。您可以删除您的 __init__
方法(由于 object.__init__
中的特殊处理,将停止 object.__init__
提示),或者你可以调用 super(Bound, self).__init__()
,不带参数。
有关详细信息,请参阅 explanatory comment在 Python 源代码中。
关于python - super 在子类化 tuple() 时给出错误的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42889064/