Multiple Inheritence with same Base Classes in Python

Posted by Jordan Reiter on Stack Overflow See other posts from Stack Overflow or by Jordan Reiter
Published on 2011-11-11T17:43:40Z Indexed on 2011/11/11 17:51 UTC
Read the original article Hit count: 233

I'm trying to wrap my head around multiple inheritance in python.

Suppose I have the following base class:

class Structure(object):
    def build(self, *args):
        print "I am building a structure!"
        self.components = args

And let's say I have two classes that inherit from it:

class House(Structure):
    def build(self, *args):
        print "I am building a house!"
        super(House, self).build(*args)

class School(Structure):
    def build(self, type="Elementary", *args):
        print "I am building a school!"
        super(School, self).build(*args)

Finally, a create a class that uses multiple inheritance:

class SchoolHouse(School, House):
    def build(self, *args):
        print "I am building a schoolhouse!"
        super(School, self).build(*args)

Then, I create a SchoolHouse object and run build on it:

>>> sh = SchoolHouse()
>>> sh.build("roof", "walls")
I am building a schoolhouse!
I am building a house!
I am building a structure!

So I'm wondering -- what happened to the School class? Is there any way to get Python to run both somehow?

I'm wondering specifically because there are a fair number of Django packages out there that provide custom Managers for models. But there doesn't appear to be a way to combine them without writing one or the other of the Managers as inheriting from the other one. It'd be nice to just import both and use both somehow, but looks like it can't be done?

Also I guess it'd just help to be pointed to a good primer on multiple inheritance in Python. I have done some work with Mixins before and really enjoy using them. I guess I just wonder if there is any elegant way to combine functionality from two different classes when they inherit from the same base class.

© Stack Overflow or respective owner

Related posts about python

Related posts about django