[英]About super and mult-inherit of python class
我使用Python 3.6.3
我有以下代码:
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()
我预计:
init child
init PP
init parent
但是我得到了:
init child
init PP
当我尝试打印MRO时,我得到了正确的答案。
print(exp.__class__.mro())
[<class '__main__.Child'>, <class '__main__.PP'>, <class '__main__.Parent'>, <class 'object'>]
为什么没有parent
打印?
Python不会自动调用Parent
__init__
。 您必须使用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()
现在的输出是:
init child
init PP
init parent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.