Is inheritance broken?
Ype Kingma
ykingma at accessforall.nl
Wed Mar 28 16:58:59 EST 2001
Jonathan,
<snip>
>
> 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?
>
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
be instantiated.)
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.
Regards,
Ype Kingma
--
email at xs4all.nl
More information about the Python-list
mailing list