gpt4 book ai didi

python - 在python中调用具有多重继承的父类

转载 作者:行者123 更新时间:2023-11-28 19:45:22 25 4
gpt4 key购买 nike

如果这个问题已经回答,我提前道歉,我只是找不到它。使用多重继承时,如何使用特定父类的方法?假设我有这样的东西

Class Ancestor:
def gene:

Class Dad(Ancestor):
def gene:
...

Class Mom(Ancestor):
def gene:
...

Class Child(Dad,Mom):
def gene:
if(dad is dominant):
#call dad's gene
else:
#call mom's gene

我该怎么做? super() 没有指定特定父级的选项。谢谢!编辑:忘记提及一个极其重要的细节——这些方法具有相同的名称并且被覆盖了。抱歉,再次感谢!

最佳答案

这不是 super 的用途。 super 只是为了调用继承层次结构中的下一项,无论它是什么 - 换句话说,当您不知道或不关心该层次结构是什么时,应该使用它。

对于您的情况,您可能只想直接调用该方法。但请注意,您实际上根本不需要处理祖先,因为 methodAmethodB 无论如何都不会被覆盖:因此您可以在 self 上调用它们:

if whatever:
self.methodA()
else:
self.methodB()

如果您处于重写方法的情况下,则需要指定祖先:

class C(A, B):
def methodA(self):
if whatever:
A.methodA(self)
else:
B.methodA(self)

关于python - 在python中调用具有多重继承的父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671889/

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