Inheritance and Design Question

Matimus mccredie at
Wed May 27 16:59:33 EDT 2009

On May 27, 12:58 pm, imageguy <imageguy1... at> 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.
> Any help suggestions would be appreciated.
> g.

>From what you have shown, there really is no _good_ reason to use
inheritance at all. Just delegate (which is the decorator pattern,
different from function decorators).

class Inner(object):
    def process(self, value):
        retval = "Parent.result('%s')" % value
        return retval

class Outer(object):
    def __init__(self, inner):
        self._inner = inner

    def process(self, value):
        retval = "Outer.result('%s')" % self._inner.process(value)
        return retval

This is a silly example, but if you can get the same thing done
without creating a direct dependence between classes then don't. You
will have to construct outer and pass it inner somewhere. If that is a
problem, then just make a factory. In python I implement factories as
just functions most of the time.

The above also encourages reuse. Now you have a decorator that could
be used anywhere.


More information about the Python-list mailing list