Multilevel Python / Mixin Inheritance

I have the following problem:

class A: animal = 'gerbil' def __init__(self): self.result = self.calculate_animal() def calculate_animal(self): print(self.animal) return self.animal class B(A): animal = 'zebra' def __init__(self): super(B, self).__init__() 

Now I want a specific set of subclasses from A to implement a new function that computes something different with an animal, for example:

 class CapitalizeAnimal: def calculate_animal(self): self.animal = self.animal.upper() # I need to call some version of super().self.animal, # but how will this Mixin class know of class A? class C(A, #CapitalizeAnimal?): animal = 'puma': def __init__(self): super(C, self).__init__() 

How do I get class C to implement the version of CapitalizeAnimal calculate_animal while keeping her animal as puma ? I'm confused about how the Mixin class can call the super () function.

+6
source share
2 answers

The order of the parent classes is important, you should do it like this:

 class C(CapitalizeAnimal, A): animal = 'puma' def __init__(self): super(C, self).__init__() 

More information can be found by reading the MRO (Order Resolution Resolution).


In addition, super only works with new style classes , so you should make A inherit object (unless, of course, you are using Python 3).

+5
source

First of all, B and C do not need __init__() if the only action calls super __init__ .

To your question: have you tried class C(A, CapitalizeAnimal): and / or class C(A, CapitalizeAnimal): :? Ie, dropping # and ? ?

0
source

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


All Articles