Python multiple inheritance constructor not called when using super()

旧巷老猫 提交于 2019-12-20 02:09:15

问题


Consider the following code:

class A(object):
    def __init__(self):
        pass
class B(object):
    def __init__(self):
        self.something = 'blue'
    def get_something(self):
        return self.something
class C(A,B):
    def __init__(self):
        super().__init__()
        print(self.get_something())

and then do:

c = C()

which results in something like this:

AttributeError: 'C' object has no attribute 'something'

I suppose this happens due to the constructor of B not being called when using super(). Is there a way to achieve the correct behavior with Python 3?


回答1:


Superclasses should use super if their subclasses do. If you add the super().__init__() line into A and B your example should work again.

Check the method resolution order of C:

>>> C.mro()
[__main__.C, __main__.A, __main__.B, builtins.object]

This article should clear things up.




回答2:


As others have mentioned, the method resolution order is key here. If you want to call multiple superclass constructors, then you will have to call them directly.

class A(object):
    def __init__(self):
        pass
class B(object):
    def __init__(self):
        self.something = 'blue'
    def get_something(self):
        return self.something
class C(A,B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)
        print(self.get_something())


来源:https://stackoverflow.com/questions/25372653/python-multiple-inheritance-constructor-not-called-when-using-super

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!