简体   繁体   English

关于python类的超级继承

[英]About super and mult-inherit of python class

I use Python 3.6.3 我使用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. 当我尝试打印MRO时,我得到了正确的答案。

print(exp.__class__.mro())

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

Why is there no print of parent ? 为什么没有parent打印?

Python doesn't automatically call __init__ of Parent . Python不会自动调用Parent __init__ You have to do it explicitly with super().__init__() in PP : 您必须使用PP super().__init__()显式地执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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