Design Question

Michael Hudson mwh at
Tue Jan 13 18:37:16 CET 2004

ferrell at (Robert Ferrell) writes:

> I have a question which is more about OO design than Python per se. 
> I've noticed that a number of posters to this list have very good
> suggestions for SE issues, so I'm hoping that someone will be able to
> give me some guidance.
> My question is about how to architect a class hierarchy where some
> methods are nearly identical between a superclass and a subclass, but
> differ slightly.  For example:
> class Sup(object):
>    def __init__(self):
>       self.specialFlag = False
>    def aMeth(self):
>        <do some stuff>
>        <if self.specialFlag, do a special thing>
>        <do more stuff>
> class Sub(Sup):
>   def __init__(self):
>     self.specialFlag = True
> In this example, the method aMeth just checks for specialFlag, and if
> it's True, does the special stuff required.
> This allows me to share aMeth, and not have to duplicate code. 
> However, this doesn't feel great to me because Sup has to know about
> Sub in some fashion.  

I'm not an OO bigot, and in some circumstances I think that
superclasses knowing about all their subclasses is just fine.

> If later I add other subclasses with their own special needs, the
> entanglement will just get worse.

If you do this, then yes.  Are you going to?  (Yes, you can feel an XP
flavour to my thoughts...).

The idea that sometimes seems to appear of almost doing battle with
your subclasses seems particularly misguided.


> I'm guessing that there is some well known pattern that addresses this
> issue, but I don't know what it is.  Does anyone have suggestions for
> architecture that provides a good solution?


class Sup(object):
   def __init__(self):
      self.specialFlag = False
   def aMeth(self):
       <do some stuff>
       <do more stuff>
   def doSpecialThing(self):

class Sub(Sup):
   def doSpecialThing(self):
       <do a special thing>

kind of suggests itself, but it's hard to say out of context whether
it applies.  You might enjoy reading Alex Martelli's talk on the
template design pattern that he gave at EuroPython 2003:


  ARTHUR:  Yes.  It was on display in the bottom of a locked filing
           cabinet stuck in a disused lavatory with a sign on the door
           saying "Beware of the Leopard".
                    -- The Hitch-Hikers Guide to the Galaxy, Episode 1

More information about the Python-list mailing list