Main Content

Multiple inheritance in Python - complete working example

Archive - Originally posted on "The Horse's Mouth" - 2010-04-14 00:04:06 - Graham Ellis

Python supports multiple inheritance, but good simple examples are very hard to find. So here is an example which I wrote during my trip to Ireland, where I was running a private Python course (link - Python courses).

I've defined two base classes - a "transport object" that provides a method to return the higher capacity of two different pieces of transport, and (in order to demonstrate decorators, classmethods and staticmethods), a method to return the highest capacity of a whole list of different transport objects.

But I can't create just a "Transport object" - I can create either public transport objects or private transport objects, both of which extend my transport class and use my first inheritance. That's fairly typical so far of any OO language.

I have then defined a class of "label object". That's a class through which I can apply a piece of text to an object - and when I get that text back out, it has been capitalized for effect.

Now - I may want to label a lot more than just transport objects, so my label objects - the attributes and all the things done with them - are not in the same class as the transport objects, but in their own class. And then I have simply included that class too in the tuple on the end of the class definitions which need multiple inheritance:
   class pubtrans(trans,label):
and it works. As easily as that.

Dorothy-2: grahamellis$ python fob
To KEEVIL carrying 4
To SWINDON carrying 150
To SEEND CLEEVE carrying 7
To LONDON PADDINGTON carrying 455
To BATH SPA carrying 61
 
Let's see is Seend or Swindon has the higher capacity
SWINDON : 150
 
Let's see which has the highest capacity of all
LONDON PADDINGTON : 455
Dorothy-2: grahamellis$


The full source code of the example may be found [here].

I said at the start that this was an easy first example. And - yes - it is. Once you start calling the base constructors of the superclass, once you start working with subclasses which inherit from several base classes which in turn inherit - and perhaps from other common classes - it starts to get more complex. Such diamond relationships ARE supported, but that's taking it rather beyond this first illustrative example which I set out to provide you with.

And let me end with a work of caution. You won't need multiple inheritance very often (that's why there aren't many examples around ...) and there are often much easier ways. See [here]. But if needs must then, yes, Python can do it.