[英]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.