简体   繁体   中英

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. 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 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.

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 :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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