我有一个 A 类:
class A(object):
def pprint(x):
print(x)
然后我有一个 B 类:
class B(object):
def pprint(x):
x += 1
# find a way to call A.pprint(x)
然后我有一个子类:
class Child(B, A):
pass
应该使用哪个:
child = Child()
child.pprint(1)
>>> 2
我可以更改 B 但不能更改 A。我不能在 B 中直接引用 A。B 永远不会直接实例化,总是通过子类实例化。
经过解释 - 你需要的不是 super()
你需要像 sibling_super()
这样的东西来找到多重继承链中的下一个类。您可以为此轮询 Python 的 MRO,例如:
class A(object):
def pprint(self, x): # just to make it valid, assuming it is valid in the real code
print(x)
class B(object):
@staticmethod
def sibling_super(cls, instance):
mro = instance.__class__.mro()
return mro[mro.index(cls) + 1]
def pprint(self, x):
x += 1
self.sibling_super(B, self).pprint(self, x)
class Child(B, A):
pass
child = Child()
child.pprint(1) # 2
我是一名优秀的程序员,十分优秀!