Is inheritance broken?

Jonathan Claggett jcc.ugm at ix.netcom.com
Wed Mar 28 21:29:23 CEST 2001


>    Jonathan> Isn't this wrong?
>
>Nope.  It's a feature of multiple inheritance, not a bug.  The search
>through base classes is left-to-right, depth first, thus
>parallelogram.angle is found before rectangle.angle.

Thank you, I think I understand now. I think the problem is that the depth
first searching works fine so long as you don't have a common ancestor in
your class tree. If you do have a common ancestor, it will be searched ahead
of some of its descendant classes. I wonder if there is a (quick) way to do
a depth first search that accounts for common ancestors...

If I really wanted this to work, guess one thing I could do is to cheat by
creating a 'flat' list of classes and then manually creating my class tree.
Something like this:

<code>

# 'flat' classes
class parallelogram_flat:
	def angle(self): return "variable"
	def side(self): return "variable"

class rhombus_flat:
	def side(self): return "same"

class rectangle_flat:
	def angle(self): return "90 degree"

class square_flat:
	pass

# 'real' classes
class parallelogram(parallelogram_flat):
	pass
class rhombus(rhombus_flat, parallelogram_flat):
	pass
class rectangle(rectangle_flat, parallelogram_flat):
	pass
class square(square_flat, rhombus_flat, rectangle_flat, parallelogram_flat):
	pass

# usage

s = square()
print "squares have", s.angle(), "angles"
print "squares have", s.side(), "sides"

</code>

Ugly and error prone, no?

>Someone with more Python years under their belt will have to answer why
>Guido chose depth first instead of breadth first search for methods when
>multiple inheritance is involved.  I'm pretty sure it's a choice that can't
>be changed now, however.  There's probably too much code that relies on the
>current semantics.

I second your question (does Guido read this list?) :-)





More information about the Python-list mailing list