多重继承 Python 与 super()

Multiple Inheritance Python with super()

我有一种情况,我必须初始化所有的基类

class B:
    def __init__(self):
        print("B.__init__")

class C:
    def __init__(self):
        print("C.__init__")

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

class E(D):
    def __init__(self):
        print("E.__init__")
        super().__init__()

x = E()

但是上面的代码导致了

E.__init__
D.__init__
B.__init__

我担心的是为什么 C 没有初始化?

当有两个child类提供方法时(这里是__init__),Python只调用一次方法,根据方法决定调用哪个解决顺序 (MRO)。

您可以通过访问 __mro__ 属性来检查 MRO。

>>> D.__mro__
(__main__.D, __main__.B, __main__.C, object)

当一个方法被调用时,首先要看的地方是D,然后是B,然后是C,然后是object

因为 super() 不会自动调用 所有 继承的方法,只会调用层次结构中的下一个方法。为了确保调用所有,你应该在 BC__init__ 方法中有 super().__init__() (在你的特定场景中你只需要将它添加到 B.