简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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