简体   繁体   English

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

[英]super() usage in multiple inheritance in python

I am new to python.我是python的新手。 I am trying to understand super() functionality in python multiple inheritance.我试图了解 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()

I am getting the following error:我收到以下错误:

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

super() will find the next method in the MRO sequence . super()将找到MRO 序列中下一个方法 This means that only one of the __init__ methods in your base classes is going to be called.只有的一个,这意味着__init__在基类的方法将被调用。

You can inspect the MRO (the Method Resolution Order ) by looking at the __mro__ attribute of a class:您可以通过查看类的__mro__属性来检查 MRO(方法解析顺序):

>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>)

so from D , the next class is B , followed by C and object .所以从D ,下一个类是B ,然后是Cobject From D.__init__() , the super().__init__() expression will only call B.__init__() , and then because C.__init__() is never called , self.c is not set either.D.__init__()super().__init__()表达式只会调用B.__init__() ,然后因为C.__init__()永远不会被调用self.c也没有设置。

You'll have to add more super() calls to your class implementations;您必须向类实现添加更多super()调用; it is safe to call object.__init__() with no arguments, so just use them everywhere here:不带参数调用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)

Now B.__init__ will invoke C.__init__ , and C.__init__ will call object.__init__ , and calling D().output() works:现在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM