New subclass vs option in __init__

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Dec 6 12:55:45 EST 2007


Kurt Smith a écrit :
> 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?

You forgot the strategy pattern : extract the different behaviours into 
other objects (in Python, usually callback functions or custom 
callables) that are passed to the initializer and called when 
appropriate. This keeps a clean encapsulation of variations (ie you 
don't have to add new conditions and tests in your class) while avoiding 
class proliferation.

Inheritance - while useful - is a bit oversold IMHO, specially in the 
context of a dynamic language. FWIW, inheritance is just a special case 
of composition/delegation...



More information about the Python-list mailing list