super 在子类化 tuple() 时给出错误的类型

super giving the wrong type when subclassing tuple()

我尝试将某些内容从 python2 移植到 python3,但遇到了有关以下 class:

的错误
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 parameterssuper(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 of object, which seems wrong – doesn't super 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__()

有关详细信息,请参阅 Python 源代码中的 explanatory comment