New subclass vs option in __init__

Kurt Smith kwmsmith at gmail.com
Thu Dec 6 11:56:30 EST 2007


Hi List:

Class inheritance noob here.

For context, I have the following base class and subclass:

class Base(object):
    def __init__(self, val):
        self.val = val

class Derived1(Base):
    def __init__(self, val):
        super(Derived1, self).__init__(val)

I'm curious as to other's thoughts on the following: when
incorporating optional behavior differences for a subclass, do you a)
make a new subclass (e.g., 'Derived2') and override (and add new)
methods that would encapsulate the new behavior, or b) keep the same
subclass around (i.e., 'Derived1'), but add an initialization option
that would specify the different behavior, and check for the value of
this option in the different methods?

It would seem that there are cases where one would be preferable over
the other: a) when the new behavior would modify a large portion of
the existing subclass, making a new subclass would be ideal; b) when
the new behavior changes only slightly the existing subclass, perhaps
a simple default option in the subclass's __init__ method would be
best.  Where is the tipping point?  Since one cannot predict what
direction the new behavior might take things, should one usually err
on the side of a new subclass?  Is option b) just being lazy?  Is a)
too verbose in many situations?

Kurt



More information about the Python-list mailing list