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

1 python super python-3.x

我是python的新手.我试图了解super()python多重继承中的功能.

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()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

AttributeError: 'D' object has no attribute 'c'
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

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

您可以通过查看类的属性来检查MRO(方法解析顺序):__mro__

>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>)
Run Code Online (Sandbox Code Playgroud)

所以D,下一堂课是B,接着是Cobject.来自D.__init__()中,super().__init__()表达只会打电话B.__init__(),然后因为C.__init__()从来没有所谓的,self.c没有设置任何.

您必须为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)
Run Code Online (Sandbox Code Playgroud)

现在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
Run Code Online (Sandbox Code Playgroud)