python 中多重继承中的 super() 用法

super() usage in multiple inheritance in python

我是 python 的新手。我正在尝试了解 python 多重继承中的 super() 功能。

class B():
    def __init__(self):
        print("__init__ of B called")
        self.b = "B"

class C():
    def __init__(self):
        print("__init__ of C called")
        self.c = "C"

class D(B, C):
    def __init__(self):
        print("__init__ of D called")
        super().__init__()

    def output(self):
        print(self.b, self.c)

d = D()
d.output()

我收到以下错误:

AttributeError: 'D' object has no attribute 'c'

super() 将在 MRO 序列 中找到 下一个方法。这意味着只有 __init__ 方法在你的基础 classes 中被调用。

您可以通过查看 class:

__mro__ attribute 来检查 MRO( 方法解析顺序
>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>)

所以从D开始,下一个class是B,然后是Cobject。从 D.__init__() 开始,super().__init__() 表达式只会调用 B.__init__(),然后因为 C.__init__() 从未调用过 self.c也没有设置。

您必须向 class 实施添加更多 super() 调用;不带参数调用 object.__init__() 是安全的,所以只需在 此处使用它们:

class B():
    def __init__(self):
        print("__init__ of B called")
        super().__init__()
        self.b = "B"

class C():
    def __init__(self):
        print("__init__ of C called")
        super().__init__()
        self.c = "C"

class D(B, C):
    def __init__(self):
        print("__init__ of D called")
        super().__init__()

    def output(self):
        print(self.b, self.c)

现在 B.__init__ 将调用 C.__init__C.__init__ 将调用 object.__init__,并且调用 D().output() 有效:

>>> d = D()
__init__ of D called
__init__ of B called
__init__ of C called
>>> d.output()
B C