[Tutor] design questions: pythonic approach to ostriches

Alan Gauld alan.gauld at freenet.co.uk
Sat Apr 23 21:18:30 CEST 2005


> I am wondering about the Pythonic way to handle the problem of
> ostriches, emus, and penguins. (I cannot recall from where I got the
> example.)

Its not really a Python issue its one of several similar conundrums in
OOP in any language.

My solution for this one:

class Bird()...

class FlightlessBird(BIrd):...

class FlyingBird(Bird):...

class Ostritch(FlightlessBird):...

class Emu(FlighlessBird):...

class Seagull(FlyingBird):...

etc.

But it gets complicated when you get more exceptions and you wind up
with
an explosion of classes. So in general there is a design pattermn that
helps out called a decorator(I hope thats the right one...).

The other approach(which I prefer) is to use a concept called a Mixin
(as mixing in flavours in an ice cream parlour - it was introduced in
the Lisp OO Language Flavors...). Mixins are little classes that
define
behaviour in a generic way. You then use multiple inheritance to
create the mix you need:

class Bird....

class Flight:.... # used for birds or planes or rockets...

class Nesting:....

class TreeDweller....

class HouseDweller...

class Swallow(Bird, Flight, HouseDweller, Nesting)....

class  Ostritch(Bird)....

class Owl(Bird,Flight, Nesting, TreeDweller)...

and so on.

But this only works well in languages that support dynamic
binding, and multiple inheritance - like Python!

But as I said similar problems exist and there is no simple answer.
You pick the one with least pain for your situation. (A common
example is where do Square and Rectangle sit in a heirarchy of
shapes?....)

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list