Derived class problem

Delaney, Timothy tdelaney at avaya.com
Mon May 27 01:48:16 EDT 2002


> From: kern at taliesen.caltech.edu [mailto:kern at taliesen.caltech.edu]
> 
> In article <Pine.GSO.4.05.10205271022440.10447-100000 at sparc41>,
> 	Geiger Ho <s997659 at ee.cuhk.edu.hk> writes:
> > Hi all,
> > 
> >   Consider,
> > 
> > class A:
> >   def method1(self):
> >       ...
> >       child = A()
> >       ...
> > 
> > class B(A):
> >   pass
> > 
> > 
> >   When I call B.method1(), I will create an A child. But 
> this is not I
> > intend to do. I wanna create a B child. Can anyone tell me how I can
> > modify? I don't want to override method1 as this is a 
> pretty big code.
> 
> Try
> 
> class A:
>     def method1(self):
>         child = self.__class__()
> 
> class B(A):
>     pass

The above is good, but doesn't take into account that B may need parameters
passed to its initialiser. Another approach is to use the Template Method
pattern.

class A:

    def method1 (self):
        ...
        child = _createChild() # Template method, _ to indicate that it is
"protected"
        ...

    def _createChild (self):
        return A()

class B (A):

    def _createChild (self):
        return B(1, 2, 3)

A further approach is to use a full-blown factory ...

Each approach has different advantages and tradeoffs (a full-blown factory
for example could have arbitrary things registered for creation, but
requires more code). In fact, the self.__class__() approach is effectively
using a built-in factory.

For your purposes, I would suggest either the self.__class__() approach (if
you don't need parameters passed to your initialisers, or they all have the
same parameters) or use a template method.

Tim Delaney





More information about the Python-list mailing list