我想你只是需要super
重定向調用父或兄弟類(取決於MRO)。
例如:
class A1(object):
def m(self):
print('Calling method m of class A1')
self.data *= 2
class A2(object):
def m(self):
print('Calling method m of class A2')
self.data *= 3
class A3(object):
def m(self):
print('Calling method m of class A3')
self.data *= 4
class B(object):
def m(self, p):
print('Calling method m of class B')
for i in range(p):
# You haven't specified which python you are using so I assume
# you might need to most explicit variant of super().
# Python3 also allows just using super().m()
super(B, self).m()
class C1(B, A1):
def __init__(self, value):
self.data = value
只是測試它:
a = C1(10)
a.m(10)
打印:
Calling method m of class B
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
和保存的值:
a.data
# returns 10485760
個
定義其他C
作品太:
class C2(B, A2):
def __init__(self, value):
self.data = value
a = C2(10).m(2)
#Calling method m of class B
#Calling method m of class A2
#Calling method m of class A2
class C3(B, A3):
def __init__(self, value):
self.data = value
a = C3(10).m(1)
#Calling method m of class B
#Calling method m of class A3
當然你會希望另一邏輯,可能需要從.m()
返回而不是就地修改值,但我認爲你可以運作他們自己。
您正在查找的單詞可能是MRO (method resolution order)。希望這可以幫助你。
另外感興趣的可能是super
(Python2),super
(Python3)的文檔。
而你總是可以通過調用.mro()
方法檢查類的MRO
:
print(C1.mro())
[<class '__main__.C1'>, <class '__main__.B'>, <class '__main__.A1'>, <class 'object'>]
所以Python開始通過檢查C1
有一個方法m
,如果不檢查B
。 B
有一個,所以它被執行。 super
調用然後再次進入MRO
並檢查下一個類(A1
)是否有方法m
,然後執行該方法。
你能舉一些例子嗎? – Yen