Python Method Overriding Tutorial

  • Post author:
  • Post category:Python

In this section, we will learn about method overriding in Python.

Note: we’re assuming you’re familiar with the Python inheritance.

Method Overriding in Python

Method overriding is the process of creating a method in a child class with the same signature as the one that a parent class already has.

Note: signature means same name, and the same number of parameters.

We mainly use method overriding when a method of the parent class doesn’t satisfy the need of a child class and so we want to create the same method but with different set of instructions in the child class.

Example: overriding a method in python

class Parent: 

    def sayHi(self):
        print("Hello from the parent class")


class Child (Parent):

    def sayHi(self):
        print("Hello from the Child class")

child = Child()

child.sayHi()

Output:

Hello from the Child class

How Does Method Overriding Work?

Note that when overriding a method in a child class, if we create an object from the child class and call that overridden method, only the one in the child class will be invoked and not the one in the parent class.

This is called method shadowing, and the reason is that Python execution engine search its way from the very child class (the one that the object is created from) and then if it can’t find the invoked method, it will move to the parent classes and look for the method. So when we override a method, there’s no reason for the execution engine to look for the target method in other classes when the child class already has one.

But if we somehow still need to invoke the same method in the parent class as well as the one we’ve overridden in the Child class, we can use the `super()` function then!

All we need to do is to call the same method in the parent class within the body of the overridden method in the child class using the super() function.

Example: Python method overriding and super() function

class Parent: 

    def sayHi(self):
        print("Hello from the Parent class")


class Child (Parent):

    def sayHi(self):
        super().sayHi()
        print("Hello from the Child class")

child = Child()

child.sayHi()

Output:

Hello from the Parent class

Hello from the Child class

Leave a Reply