There are often times when inheriting from a parent class you need to extend a method without overwriting it so you can execute the code that is contained in the parent module without having to rewrite it. In this post I will show you how to do that with pythons "super" method.

Lets take a look at the code snippet below I define a class that has a method called my_func and that method just executes a simple print statement.

class MyBaseClass:
    def my_func(self):
        print('This print statement is from the base class.')

And if that function executes we would get the output below.

$ python test.py
This print statement is from the base class.

 

Extending through inheritance - This is polymorphism

Now if we want access to that method in another class we can inherit MyBaseClass which is all good but lets say we want to extend that method but do not want to overwrite the method which would require us to repeat the code. This is where the Python super method can save us, it allows the code in the parent classes method to be preserved when we overwrite a method in a child class. Taking a look at the code snippet below we can see the syntax of how this is done

class ChildClass(MyBaseClass):
    def my_func(self):
        super().my_func()
        print('This print statement is from the child class.')

If you look at line 3 of the code snippet this is where the parent classes my_func method is called and then we are able to extend it with our own code afterward. So below I have a module containing both classes and configured to run the child class when run directly.

class MyBaseClass:

    def my_func(self):
        print('This print statement is from the base class.')

class ChildClass(MyBaseClass):

    def my_func(self):
        super().my_func()
        print('This print statement is from the child class.')


if __name__ == '__main__':
    t = ChildClass()
    t.my_func()

So if we run this file we get the output below.

$ python test.py
This print statement is from the base class.
This print statement is from the child class.

As you can see our parent classes my_func method executes first and then the rest of the code is executed and we were able to successfully extend our method.

One other thing you can do with the module above is flip line numbers 9 and 10 making our super call come after our child methods print statement, then our child classes print statement will print first then our parent module. This gives gives us the flexibility of executing the code in the parent classes module at any specific time in the child module allowing us to reuse existing code.