我想你只是需要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