[英]super() usage in multiple inheritance in python
我是python的新手。 我試圖了解 python 多重繼承中的super()
功能。
class B():
def __init__(self):
print("__init__ of B called")
self.b = "B"
class C():
def __init__(self):
print("__init__ of C called")
self.c = "C"
class D(B, C):
def __init__(self):
print("__init__ of D called")
super().__init__()
def output(self):
print(self.b, self.c)
d = D()
d.output()
我收到以下錯誤:
AttributeError: 'D' object has no attribute 'c'
super()
將找到MRO 序列中的下一個方法。 只有的一個,這意味着__init__
在基類的方法將被調用。
您可以通過查看類的__mro__
屬性來檢查 MRO(方法解析順序):
>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>)
所以從D
,下一個類是B
,然后是C
和object
。 從D.__init__()
, super().__init__()
表達式只會調用B.__init__()
,然后因為C.__init__()
永遠不會被調用, self.c
也沒有設置。
您必須向類實現添加更多super()
調用; 不帶參數調用object.__init__()
是安全的,所以只需在此處隨處使用它們:
class B():
def __init__(self):
print("__init__ of B called")
super().__init__()
self.b = "B"
class C():
def __init__(self):
print("__init__ of C called")
super().__init__()
self.c = "C"
class D(B, C):
def __init__(self):
print("__init__ of D called")
super().__init__()
def output(self):
print(self.b, self.c)
現在B.__init__
將調用C.__init__
,而C.__init__
將調用object.__init__
,並且調用D().output()
工作:
>>> d = D()
__init__ of D called
__init__ of B called
__init__ of C called
>>> d.output()
B C
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.