[英]How do I initialize this derived class that uses multiple inheritance?
假設我有一個名為Vehicle
的 class ,並且我有兩個名為Boat
和Car
的子類,它們繼承自Vehicle
。
現在說我有一輛兩棲車輛,它使用多個 inheritance AmphibiousVehicle(Boat, Car)
。
現在我的問題是: AmphibiousVehicle
的__init__
function 應該如何定義?
Boat
和Car
都通過調用super().__init__()
來初始化Vehicle
。
我需要在AmphibiousVehicle
的 init 中一一初始化Boat
和Car
嗎?
或者我可以只調用一次super
嗎? 如果我這樣做,我看不到Car
是如何初始化的?
Python 使用協作多個 inheritance 。 這意味着您對super()
的調用不一定會到達調用它的基本 class,它會按照您開始的方法解析順序(MRO) 到達下一個 class。
展示:
class A:
def __init__(self):
print("A.__init__")
super().__init__()
class B:
def __init__(self):
print("B.__init__")
super().__init__()
class C(A, B):
def __init__(self):
print("C.__init__")
super().__init__()
c = C()
給出 output:
C.__init__
A.__init__
B.__init__
So the call super().__init__()
inside class A
calls __init__()
in class B
, even though class A
does not inherit from class B
.
只要你所有的類確保他們在適當的地方調用super
,你只需要調用一次並相信一切都會合作。
MRO 基本上是 python 將在類中搜索方法或屬性的順序。 您可以通過檢查 class 上的__mro__
屬性來檢查此順序是什么:
print(C.__mro__)
給我們:
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.