我认为您只需要 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,然后执行该方法。