Skip to content Skip to sidebar Skip to footer

Python Multiple Inheritance Constructor Not Called When Using Super()

Consider the following code: class A(object): def __init__(self): pass class B(object): def __init__(self): self.something = 'blue' def get_something(se

Solution 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.

Solution 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.

classA(object):
    def__init__(self):
        passclassB(object):
    def__init__(self):
        self.something = 'blue'defget_something(self):
        return self.something
classC(A,B):
    def__init__(self):
        A.__init__(self)
        B.__init__(self)
        print(self.get_something())

Post a Comment for "Python Multiple Inheritance Constructor Not Called When Using Super()"