user3134477 user3134477 - 19 days ago 5
Python Question

Python - create additional statements when calling inherited method

Let's say I have this:

class Foo:
...
def func():
return 1+2

class Bar(Foo):
...
def another_func():
# additional stuff I want to do when my parent's func() is called


I don't want to override
func
, but I do want to add some additional statements when it's called. Also, I don't want to change the original
Foo.func
.

Is it even possible? If not, any idea for a workaround?

Answer

You need to override the func function and make the call to parent's func from within it. Python has super() for that purpose:

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

Example:

class Foo(object):    
    def func(self):
        print "In parent"

class Bar(Foo):
    def func(self):
        super(Bar, self).func()
        print 'In child'   # Your additonal stuff

When you will run the func of Bar as:

b = Bar()
b.func()

will print:

In parent   #  <-- from Foo.func()
In child    #  <-- from Bar.func()