简体   繁体   English

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

[英]Calling parent class with multiple inheritance in python

I'm apologizing in advance if this question was already answered, I just couldn't find it. 如果这个问题已经得到解答,我提前道歉,我找不到它。 When using multiple inheritance, how can I use a method of a specific parent? 使用多重继承时,如何使用特定父级的方法? Let's say I have something like this 假设我有类似的东西

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

How can I do that? 我怎样才能做到这一点? The super() doesn't have the option the specify the specific parent. super()没有指定特定父级的选项。 Thanks! 谢谢! Edit: Forgot to mention an extremely important detail - the methods are of the same name and are overridden. 编辑:忘了提一个非常重要的细节 - 这些方法具有相同的名称并被覆盖。 Sorry, and thanks again! 对不起,再次感谢!

That's not what super is for. 这不是super用的。 super is just meant to call the next item in the inheritance hierarchy, whatever it is - in other words, it's supposed to be used when you don't know or care what that hierarchy is. super只是用于调用继承层次结构中的下一个项目,无论它是什么 - 换句话说,它应该在您不知道或不关心该层次结构时使用。

For your case, you probably just want to call the method directly. 对于您的情况,您可能只想直接调用该方法。 But note that you don't actually need to deal with ancestors at all, because methodA and methodB are not overridden anyway: so you can just call them on self : 但请注意,你实际上并不需要在所有处理的祖先,因为methodAmethodB不反正覆盖:所以你可以打电话给他们的self

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

If you are in the situation where you have overridden methods, you will need to specify the ancestors: 如果您处于重写方法的情况,则需要指定祖先:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM