Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Multiple Inheritance/Mixin

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 certain set of subclasses from A, to implement a new function that calculates something different with the animal, like so:

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 CapitalizeAnimal version of calculate_animal, while keeping its animal as puma? I'm confused at how the Mixin class will be able to call a super() function.

like image 940
atp Avatar asked Aug 19 '11 19:08

atp


1 Answers

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

class C(CapitalizeAnimal, A):
     animal = 'puma'

     def __init__(self):
         super(C, self).__init__()

More info can be found by reading about the MRO (Method Resolution Order).


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

like image 108
mouad Avatar answered Nov 08 '22 01:11

mouad