gpt4 book ai didi

python - 从父类B使用父类A的方法

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:04 25 4
gpt4 key购买 nike

我有一个 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

关于python - 从父类B使用父类A的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45361979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com