Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python super() - should be working but isn't?

As far as I can tell, and everything I've been finding online, this should work (but it doesn't, which is why I'm asking here ;) )

class Tigon(Crossbreeds, Predator, Lion):

    def __init__(self):
        super().__init__()
    def printSize(self):
        print("Huge")

Both "Crossbreeds" and "Predator" inherit from "Mammal", and "Lion" inherits from Predator. The compilation of those works fine. I'm working on Python 3.2, though I did also try the earlier:

Edit: Sorry, part of my post didn't come through for some reason.

I also tried:

class Tigon(Crossbreeds, Predator, Lion):

    def __init__(self):
        super(Tigon, self).__init__()
    def printSize(self):
        print("Huge")

and both of them gave me:

class Tigon(Crossbreeds, Predator, Lion):
TypeError: Cannot create a consistent method resolution
order (MRO) for bases Predator, Mammal, Lion

Any suggestions?

like image 223
BIU Avatar asked May 19 '11 10:05

BIU


People also ask

How does super () work in Python?

The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.

Is super () necessary Python?

In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).

What is super () __ init __ in Python?

The “__init__” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. Python super() The super() function allows us to avoid using the base class name explicitly.

How do you call super super Python?

To call a super() function in Python, create a parent and child class and inherit parent class to child class and then call super() method from the child class. First, we will take a regular class definition and modify it by adding the super function.


1 Answers

Short answer: Don't inherit the same base class directly and indirectly, but inheriting directly after indirectly should work. So don't inherit Predator or inherit it after Lion.

Well, the C3 MRO seems to not be able to find any order consistent with all constraints. The constraints are that:

  • each class must come before it's base classes
  • and the base classes must come in the order they are listed.

You inherit Crossbreeds, Predator and Lion in that order, so their methods must be called in that order. But since Lion inherits Predator, it's methods must be called before those of Predator. Which is not possible, therefore it says it can't create consistent method resolution order.

like image 66
Jan Hudec Avatar answered Oct 03 '22 09:10

Jan Hudec