我想你只需要
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
有一个,所以它被执行。这个
超级的
呼叫然后再次进入
MRO公司
并检查下一节课(
A1
)有一个方法
米
,然后执行。