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

标签 python inheritance tuples super

我尝试将某些东西从 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 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__(),不带参数。

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

关于python - super 在子类化 tuple() 时给出错误的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42889064/

相关文章:

python - 备份 ZODB blob 的正确方法是什么?

python - 什么是 python 中的 super (类型)?

inheritance - Haxe - 如何将变量声明为父类或子类的实例

python - 将元组中元素的差异追加到列表中

python - 将多个过滤器应用于元组列表

python - python 中的评估安全性,从 JSON 中提取字符串

python - 为什么 python dict 更新出奇地慢?

python - QuickSort 返回正确的值,但未就地排序

c++ - 误解了 vector 中的虚函数

python - 如何将整列附加到 python 中的表(列表列表)?