6

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.

2 Answers 2

5

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).

Sign up to request clarification or add additional context in comments.

4 Comments

Because A is second, won't its version of calculate override CapitalizeAnimal's implementation?
Sorry, I made my question more complex. I'm not sure how CapitalizedAnimal would handle knowing of the attributes of class C, and return a super() on class A
@Manny D: yes if you make the inheritance like this: class C(A, CapitalizeAnimal) so the A.CapitalizeAnimal will be called only, unless if you are calling already super in A.CapitalizeAnimal which in this case all the mro will be traversed.
@Jasie: if you want to call only the calculate_animal of A so you add in your Mixin A.calculate_animal(self) , but if you want to call all the calculate_animal of classes that are in the MRO so use super instead.
0

First of all, B and C don't need __init__() if the only action is calling the super __init__.

To your question: Have you tried class C(A, CapitalizeAnimal): and/or class C(A, CapitalizeAnimal):? I.e., omitting the # and the ??

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.