Search code examples
pythonclassmultiple-inheritance

About super and mult-inherit of python class


I use Python 3.6.3

I have following code:

class Parent:
    def __init__(self, **kw):
        print("init parent")

class PP:
    def __init__(self, **kw):
        print("init PP")


class Child(PP, Parent):
    def __init__(self, **kw):
        print("init child")
        super().__init__()

exp=Child()

I expect:

init child
init PP
init parent

but I got:

init child
init PP

when I try to print the MRO,I got the correct answer.

print(exp.__class__.mro())

[<class '__main__.Child'>, <class '__main__.PP'>, <class '__main__.Parent'>, <class 'object'>]

Why is there no print of parent?


Solution

  • Python doesn't automatically call __init__ of Parent. You have to do it explicitly with super().__init__() in PP:

    class Parent:
        def __init__(self, **kw):
            print("init parent")
    
    class PP:
        def __init__(self, **kw):
            print("init PP")
            super().__init__()
    
    
    class Child(PP, Parent):
        def __init__(self, **kw):
            print("init child")
            super().__init__()
    
    exp = Child()
    

    Now the output is:

    init child
    init PP
    init parent