Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to access super class method in multiple inheritance

Tags:

python

class Animal(object):
    def eat(self):
        print("I eat all")

class C(object):
    def eat(self):
        print("I too eat")

class Wolf(C, Animal):
    def eat(self):
        print("I am Non Veg")
        super(Wolf, self).eat()
        Animal.eat(self)

w = Wolf()
w.eat()

I am learning multiple inheritance in python, I want to access Animal and C method eat from derived class using super method.

Default call of super inside calls C class method eat, but to call Animal class method I used Animal.eat(self) .My question is how can I call Animal class method using super method.

like image 346
Kracekumar Avatar asked Sep 14 '11 12:09

Kracekumar


2 Answers

If you want to do sane multiple inheritance, you need everyone to be calling super except exactly one base class, which has as its duty not to call super. Having two completely-independent base classes with the same method isn't something that makes sense using OOP theory and is not something that Python has the tooling to handle well.

You might see two apparently-independent base classes used in a lot of examples, but in those cases the example method is usually __init__, and the single non-super-calling base class for it is object.

like image 139
Mike Graham Avatar answered Oct 06 '22 16:10

Mike Graham


You can't call Animal.eat using super. super uses Python's Method Resolution Order (MRO) to figure out which class to call, and C is overshadowing Animal in that MRO.

In your example, super(Wolf, self).eat() has the same effect as C.eat(self). Calling Animal.eat(self) works, but only as long as the inheritance graph stays the way it currently is.

Having to call a method that's not available due to the MRO is an indication that the class modelling needs to be improved.

like image 36
phihag Avatar answered Oct 06 '22 16:10

phihag