Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Inheritance with same Base Classes in Python

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.

Yup, silly me. It was a typo all along. I feel very dumb. I promise, I always put the right class in when I super in real life, it was only when I was cutting and pasting to try this out that I messed up.

like image 324
Jordan Reiter Avatar asked Nov 11 '11 17:11

Jordan Reiter


1 Answers

Your super() call in SchoolHouse is wrong.

It is:

super(School, self).build(*args)

It should be:

super(SchoolHouse, self).build(*args)
like image 103
Sven Marnach Avatar answered Nov 15 '22 07:11

Sven Marnach