Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling parent class with multiple inheritance in python

Tags:

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!

like image 930
Idan Avatar asked Mar 17 '26 07:03

Idan


1 Answers

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)
like image 160
Daniel Roseman Avatar answered Mar 19 '26 20:03

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!