philippe
philippe

Reputation: 3189

python overriding method without re-copying whole code

I have a class Father whom I call run method to do the work. I inherit this class with a Child class. This look like this:

class Father:
    def __init__(self):
        ...

    def run(self):
        work1()
        work2()
        ....

class Child(Father):
    def run(self):
        pass

Usually, I use pass, as most of the time, children do same things as father, just being called from distinct contexts. However, sometimes the behavior changes. But when it does, work1, work2, and so on from Father are still being executed. Only a last workn should be added.

How is it possible to override run method without having to copy the whole code from Father.run, and just adding a last work instruction? I have tried this, which is working:

class Father:
    def run(self):
        work1()
        ...
        run_additionnal_stuf()
    def run_additionnal_stuf(self):
        pass

class Child(Father):
    def run_additionnal_stuf(self):
        work()

However, is there any solution more elegant?

Upvotes: 1

Views: 421

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19414

First of all, if your Child class doesn't change a method you don't need to define it with pass. Simply do nothing and thanks to inheritance magic, the child instance will also have that method.


As to your actual question, if you only want to add functionality to a child instance, you can use super. Indeed, from the docs:

This is useful for accessing inherited methods that have been overridden in a class.

So you could do:

class Child(Father):
    def run(self):
        super().run()
        work_n()

A simple demonstration:

class Father:
    def run(self):
        print("In Father")

class Child(Father):
    def run(self):
        super().run()
        print("In Child")

f = Father()
c = Child()
f.run()
c.run()

And this expectedly prints out:

In Father
In Father
In Child

Upvotes: 2

Related Questions