Is inheritance broken?
ykingma at accessforall.nl
Thu Mar 29 00:03:56 CEST 2001
> 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:
> # '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:
> # 'real' classes
> class parallelogram(parallelogram_flat):
> class rhombus(rhombus_flat, parallelogram_flat):
> class rectangle(rectangle_flat, parallelogram_flat):
> class square(square_flat, rhombus_flat, rectangle_flat, parallelogram_flat):
> # usage
> s = square()
> print "squares have", s.angle(), "angles"
> print "squares have", s.side(), "sides"
> Ugly and error prone, no?
This code follows a rule: never instantiate a class that
is inherited from. (In other languages your 'flat' classes
might be called 'abstract' in order to indicate that they cannot
IIRC this is a design pattern in class hierarchies.
In this particular case you avoid having a real square that
inherits from a real rectangle. In geometry a square
is a special case of rectangle. However this special case
from geometry is not implemented well by using OO inheritance.
The 'flat' and 'real' approach in the above class hierarchy
feels a lot better. It allows more choice of where to put
eventual attributes (eg. side length).
So, no it's not ugly at all, quite the contrary.
(Being non native in English, I don't know what a rhombus is,
so I might change my mind...)
It's also not really error prone: you only need to check
right to left, there is no need to go deeper into
the inheritance hierarchy.
email at xs4all.nl
More information about the Python-list