Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - create additional statements when calling inherited method

Tags:

python

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?


1 Answers

There is no way of doing that, the canonical solution would be to overide func und wrap the original function like so:

class Bar(Foo):
    ...
    def func():
        # additional stuff I want to do when my parent's func() is called
        res = super(Bar, self).func()  # super().func() on Py3
         # additional stuff I want to do after my parent's func() is called
        return res
like image 171
zabeltech Avatar answered Jun 16 '26 00:06

zabeltech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!