Design Question

Robert Brewer fumanchu at
Tue Jan 13 19:02:51 CET 2004

> 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.

Since classes in Python are "first class objects" just like instances, I
often modify arrangements like your example to:

class Sup(object):
    specialFlag = False
    def aMeth(self):
        if self.specialFlag:

class Sub(Sup):
    specialFlag = True

If you never assign self.specialFlag, it remains a "class attribute"
(that is, since specialFlag is never bound to the instance, it continues
to be looked up in the class dict).

Once you've done *that*, you then see further options. In my designs, I
tend to eliminate such flags, replacing them with the actual behavior
which the flag references:

class Sup(object):
    specialThing = []
    def aMeth(self):
        for eachItem in self.specialThing:

class Sub(Sup):
    specialThing = [1, 2, 3]


class Sup(object):
    specialThing = lambda x: None
    def __init__(self):
        self.x = 0
        self.y = 0
    def aMeth(self):
        self.y = self.specialThing(self.x)

class Sub(Sup):
    specialThing = lambda x: x[4] + 3

Which one you choose will be dependent upon your design.

Robert Brewer
Amor Ministries
fumanchu at

More information about the Python-list mailing list