Search code examples
pythonmultiple-inheritance

Multiple Inheritance Python with super()


I have a situation where I have to initialize all the base classes

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()

But the above code results in

E.__init__
D.__init__
B.__init__

My concern is Why wasn't C initialized?


Solution

  • When two child classes provide the method (here it's __init__), Python calls the method only once and decides which one to call based on the method resolution order (MRO).

    You can inspect the MRO by accessing the __mro__ attribute.

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

    When a method is invoked, the first place to look is D, then B, then C, then object.