Inheritance and Design Question

Carl Banks pavlovevidence at gmail.com
Thu May 28 02:44:39 EDT 2009


On May 27, 12:58 pm, imageguy <imageguy1... at gmail.com> wrote:
> I have an object the I would like to use as a base class.  Some of the
> methods I would like to override completely, but others I would simply
> like to call the base class method and use the return value in the
> child method.  The purpose here is to eliminate the duplication of
> valuable code in the parent, when I really just need the child to
> operate of a results of the parent.
>
> Consider the following two classes;
>
> class Parent(object):
>     def process(self, value):
>         retval = "Parent.result('%s')" % value
>         return retval
>
> class Child(Parent):
>     def __init__(self):
>         Parent.__init__(self)
>
>     def process(self, value):
>         retval = "Child.result('%s')" % super(Child, self).process
> (value)
>         return retval
>
> So ....
>
> foo = Child()
> print foo.process('the value')
>
> >> Child.result('Parent.result('the value')')
>
> IS there another pattern or idiom that would accomplish this?
> This seems a bit 'smelly' to me.  Also seems almost the inverse of
> decorators, but I am not sure decorators would be appropriate in this
> case.

I see nothing wrong with it, although if it is possible and convenient
to rename the base class method, as Andre Engels suggests, then that's
usually how I'd do it.

Sometimes it's not convenient to choose a different name for the base
class method, such as when you have several subclasses, most of which
don't override the method, but a few do.  In that case I'd do it same
way as you did.

One thing that does smell is your use of both old-style base class
access (Parent.__init__(self)) and newer-style (super
(Child,self).process()) in the same class.  Pick one method and stick
with it.


Carl Banks



More information about the Python-list mailing list