Search code examples
pythoninheritanceimplementationdecoratorwrapper

python parent class 'wrapping' child-class methods


I have the following situation in my python code:

class Parent(object):
    def run(self):
        print "preparing for run"
        self.runImpl()
        print "run done"

class Child(Parent):
    def runImpl(self):
        print "child running"

However, I have cases with several generations of such 'decorators', doing different setup/teardown steps before and after 'runImpl', and currently I am forced to define run(), runImpl() and runImplSingleProcess() in my classes Parent, Child and ChildSingleProcess.

I am looking for a solution of the following form:

class Parent(object):
    @wrapping_child_call
    def run(self, func_impl, *args, **kwargs)
        print "preparing for run"
        func_impl(*args, **kwargs)
        print "run done"

class Child(Parent):
    def run(self):
        print "child running"

In this way, there is almost no need for Child class to be aware of this going on.

There may also be an issue with multiple inheritance. If a Child inherits from Parent1 and Parent2, I honestly don't know what should be the correct behavior.

Does anyone know a good, natural, way of accomplishing this? or am I raping the design here?

Thanks
Yonatan


Solution

  • Don't use inheritance here

    Invert your design. Instead of a parent-child implementation which is a "is-a" relationship why not just have a composition so you get a "has-a" relationship? You could define classes which implement the methods you'd like while your previous parent class would be instantiated with those implementation specific classes.

    class MyClass:
        def __init__(self, impl)
            self.impl = impl
        def run(self,var):
            print "prepare"
            impl.runImpl(var)
            print "I'm done"
    
    class AnImplementation:
        def runImpl(self,var):