Python super () - should work, but no?

As far as I can tell, and everything I found on the Internet should work (but it’s not, so I ask 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 inherit from Predator. The compilation of these works is beautiful. I am working on Python 3.2, although I also tried before:

Edit: Sorry, part of my post failed 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?

+6
source share
3 answers

Short answer: Do not inherit the same base class directly and indirectly, but inheritance immediately after should work indirectly. Therefore, do not inherit Predator or inherit it after Lion .

Well, the C3 MRO doesn't seem to be able to find any order that matches all the restrictions. Limitations are as follows:

  • each class must have base classes
  • and base classes should be in the order in which they are listed.

You inherit Crossbreeds , Predator and Lion in this order, so their methods must be called in that order. But since Lion inherits from Predator , its methods must be called before those specified in Predator . This is not possible, so he says that he cannot create a consistent method resolution order.

+7
source

Must be super().__init__(self) .

Edited: Sorry, you have to put Lion forward:

 class Tigon(Lion, Predator, Crossbreeds): def __init__(self): super().__init__() 
0
source

If I understand the inheritance model that you described correctly, here is how you should define the Tigon class:

 class Mammal(object): def __init__(self): super(Mammal, self).__init__() class Crossbreeds(Mammal): def __init__(self): super(Crossbreeds, self).__init__() class Predator(Mammal): def __init__(self): super(Predator, self).__init__() class Lion(Predator): def __init__(self): super(Lion, self).__init__() class Tigon(Lion, Crossbreeds, Predator): def __init__(self): super(Tigon, self).__init__() t = Tigon() 

this alternative is equivalent as Lion is a predator:

 class Tigon(Lion, Crossbreeds): def __init__(self): super(Tigon, self).__init__() 

Now here is a brief rule for this. Each class constructor is called after the base classes, but they should appear in the reverse order in the class definition. In addition, classes that override the methods defined in their parent class (s) must first be displayed in the class definitions - this means that if you want to override the Predator method in Lion, Lion must appear before the Predator in the definition. A longer explanation of this is in Jan Hudeck's answer .

0
source

Source: https://habr.com/ru/post/888524/


All Articles