3 回答

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個贊
我不完全明白為什么會這樣,但我可以告訴你如何解決它:
出于某種原因,Python 只調(diào)用__init__其父項(xiàng)之一的方法。但是,這可以解決您的問題:
class Base1:
def __init__(self):
super().__init__()
print('b1')
self.x=10
class Base2:
def __init__(self):
super().__init__() # This line isn't needed. Still not sure why
print('b2')
self.y=10
class Derv (Base1, Base2):
def __init__(self):
super().__init__()
d = Derv()
print (d.__dict__)
'b2'
'b1'
{'y': 10, 'x': 10}
更新,添加打印語句實(shí)際上對這種情況有所了解。例如,
class Base1:
def __init__(self):
print('Before Base1 call to super()')
super().__init__()
print('b1')
self.x=10
class Base2:
def __init__(self):
print('Before Base2 call to super()')
super().__init__() # No remaining super classes to call
print('b2')
self.y=10
class Derv (Base1, Base2):
def __init__(self):
super().__init__()
d = Derv()
print (d.__dict__)
'Before Base1 call to super()' # Just before the call to super
'Before Base2 call to super()' # Just before call to super (but there are no more super classes)
'b2' # Calls the remaining super's __init__
'b1' # Finishes Base1 __init__
{'y': 10, 'x': 10}

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個贊
當(dāng)一個類從多個超類繼承,并且有 2 個或更多沖突方法時(shí),將調(diào)用第一個列出的類中的方法。因?yàn)閮烧?code>Base1和Base2
定義__init__
,__init__
在第一個列出的類中的版本被調(diào)用,因此沒有定義這兩個屬性。

TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個贊
這在Python docs 中有更好的解釋。
對于大多數(shù)目的,在最簡單的情況下,您可以將搜索從父類繼承的屬性視為深度優(yōu)先,從左到右,而不是在層次結(jié)構(gòu)重疊的同一類中搜索兩次。因此,如果在 DerivedClassName 中找不到屬性,則在 Base1 中搜索它,然后(遞歸地)在 Base1 的基類中搜索,如果在那里找不到,則在 Base2 中搜索,依此類推。
然后,就像__init__
在你左邊的班級中第一次找到的那樣,它不會尋找其他人。正如其他用戶所解釋的,super()
應(yīng)該用于讓 Python 知道如何尋找其他__init__
方法。
添加回答
舉報(bào)