advice on programming style: is multiple inheritance bad?

Dietrich Epp dietrich at zdome.net
Sun Feb 1 16:26:12 EST 2004


Since you asked for advice on programming style <grin>...

The argument for single inheritance is that objects should only have 
one "is a" relationship.  Penguin "is a" bird.  For multiple 
inheritance, Penguin "is a" swimmer also.  However, to keep everything 
clear, I would try to make sure each object has only one "is a" 
inheritance, and all the other inheritances are "does", e.g., Penguin 
"is a" bird, "does" fly.  If an object really does have two "is a" 
relationships, try to use two objects.  For example:

class AirlineReservation(Person, SeatOnAirplane):
     pass

This is kinda dumb and obvious, but it shows how multiple "is a" 
relationships can be total nonsense.  There are probably times when 
multiple "is a" relationships make sense, but most of the time it's 
just bad program design.  It looks like your SuperA is a "does" 
class... personally, I would name the types of classes differently, but 
that's up to you.

class Bird:
     def WhoAmI(self):
         return "bird"

# or DoesSwim, CanSwim, whatever... I'd pick one keep it consistent
class Swimming:
	def Swim(self):
		print "A %s goes SPLASH!" % self.WhoAmI()

class Penguin(Bird, Swimming):
	def WhoAmI(self):
		return "penguin"

I think pure single inheritance without mixins is bad language design.  
  Arguments against multiple inheritance usually involve overlapping 
superclasses, and every time I have seen it it *has* been bad design... 
but does anyone have overlapping superclasses that they can't separate? 
  I'm curious.

On Feb 1, 2004, at 10:48 AM, Uwe Mayer wrote:

> I got a class A2 that needs to inherit from class A1.
> A2, as well as some other classes implement a same functionality and in
> order to prevent code duplication I'd like to factorize that 
> (potentially)
> duplicate code into a class SuperA from which then A2 and all other 
> classes
> could inherrit.
> However, this would cause A2 to have two super classes A1 and SuperA - 
> which
> is possible of course in Python.
>
> My question is: is that bad programming style?
>> From C++ and Java we "learn" that you shouldn't do that.
>
> Class A is automatically generated from other tools, so I can't solve 
> the
> problem by just letting A1 inherit from SuperA.
>
> Your opinions?






More information about the Python-list mailing list