Rico
Rico

Reputation: 6042

Pythonic Approach to Multiple Parent Method Calls

Suppose I have the following class structure:

class Mixin1(Base1):
    def get_data(self):
        # Gather some data in some way


class Mixin2(Base2):
    def get_data(self):
        # Gather some data in another way


class MyClass(Mixin1, Mixin2):
    def get_data(self):
        # Gather some data in yet another way.  Then...
        # Get Mixin2's version of get_data.  Then...
        # Get Mixin1's version of get_data.

An example case to provide some context is that Mixin1 is an authentication handler and Mixin2 is a login handler. The functionality in the parent classes will populate instance variables (say, error messages).

What would be the most Pythonic approach to calling the parent's get_data methods?

One approach to get this kind of information might be something like this:

original_class = self.__class__.__base__
parents = [base for base in original_class.__bases__]
for parent in parents:
    parent.get_data()

I don't see this as an unreasonable approach but if I have to start crawling into the meta I begin to wonder if there is a more Pythonic approach.

Any suggestions? Is it possible to use super() for this?

Upvotes: 2

Views: 111

Answers (1)

Honza Osobne
Honza Osobne

Reputation: 2719

class MyClass(Mixin1, Mixin2):
    def get_data(self):
        # do local stuff
        data2 = Mixin2.get_data(self)
        data1 = Mixin1.get_data(self)

Also, this post seems to be related.

Another approach is to use containment instead of inheritance.

Upvotes: 4

Related Questions