Method Overriding in Python (with Example)

Method overriding means redefining a method in a child class to replace the functionality of the parent class method. It is an important object-oriented programming feature in Python or any other OOP languages.

When the method of superclass or parent class is overridden in the subclass or child class to provide more specific implementation, it is called method overriding in Python.

In simple words, when the superclass method is available to subclass by default through inheritance and subclass does not satisfy with superclass implementation, the subclass can redefine that method on its requirement. This feature is called method overriding.

Overriding means modifying the inherited behavior of superclass methods in a subclass. The main purpose of method overriding is to change the functionality or behaviour of the method according to the needs of the subclass that is already defined in its superclass. It occurs only when the signatures of the superclass and subclass methods are identical.

To override a method in a subclass, we must define the method in the subclass using the same signature and same return type (or sub-type) as a method defined in its superclass. Look at the below figure to be more clear.

An example of method overriding in Python

In the above code, the start method in the Car class is overriding the start method in the Vehicle class. The subclass Car provides its specific implementation of the start method, which replaces the generic implementation of the superclass Vehicle.

Overridden Method and Overriding Method in Python


Overridden Method:

An overridden method is a method that is defined in the superclass (or parent class) and is redefined in a subclass (or child class) to provide a specific implementation. This method has the same name, same parameters or signature and same return type in both the superclass and the subclass.

When we call this method on an object of the subclass, it will execute the implementation provided in the subclass, overriding the behavior inherited from the superclass.

Overriding Method:

An overriding method is a method defined in the subclass that redefines or overrides the superclass method by providing a specific implementation according to the needs of the subclass.

When we call this method on an object of the subclass, it executes the overriding implementation from the subclass rather than the implementation in the superclass. In other words, the overriding method in the subclass will execute instead of the overridden method in the superclass. We use overriding methods to modify or extend the behavior of inherited methods from the superclass.

When to Use Method Overriding in Python?


By default, a child class inherits methods from its parent class via inheritance. If you don’t satisfy with the implementation (or behavior) of an inherited method, you do not need to modify that method in the superclass. This is because the change in the code inside method is not a good idea. You should inherit that class and override it by specifying a new implementation in the subclass.

Consider the below example program to understand the need for method overriding in Python. Suppose that a young couple wants to marry. They have fixed the date of engagement and marriage. Let’s write the program code for it.

class Marry:
    def engagementDate(self):
        print("Engagement will be done on 23 Dec.")

 # Overridden method.
   def marryDate(self):
       print("Marry will be on 25 Dec")

Because of Christmas day on 25 Dec, the young couple wants to change the date of marrying. So, what will you do?

You will open class and change the date of marrying. It is the worst programming practice in Python because, as per the object-oriented programming concept, the best practice is that you should not open the class for modification.

If you want to add new functionality or behavior to the existing class or if you want to modify or update the existing functionality of the class, you should not disturb the existing class. You should always create a subclass of the existing class and add new functionality in subclass like this:

class Marry:
    def engagementDate(self):
        print("Engagement will be done on 23 Dec.")

 # Overridden method
    def marryDate(self):
        print("Marry will be on 25 Dec")

class Change(Marry):
 # Overriding method
    def marryDate(self):
        print("Marry will be on 27 Dec")

# Create an instance of subclass Change.
obj = Change()

# Call methods of subclass. 
obj.engagementDate()
obj.marryDate()
Output:
       Engagement will be done on 23 Dec.
       Marry will be on 27 Dec

In the above code, we have implemented marryDate() method in the subclass Change with the same signature as in the superclass marryDate() method. In other words, the subclass Change is overriding marryDate() method of superclass Marry. Hope that you will have understood the need or purpose of method overriding feature provided by Python with the help of this example code.

Key Features of Method Overriding in Python


Method overriding is a very important concept in OOP that allows a subclass to provide a particular implementation for a method that is already defined in its superclass. It enables us to customize the behavior or functionality of a method in the subclass while maintaining the same method signature as in the superclass.

There are the following key features and characteristics of the method overriding in Python. They are as follows:

  • Method overriding concept supports the runtime polymorphism.
  • It allows us to override inherited methods from the superclass in the subclass. In other words, it allows us to customize the behavior of the subclass without modifying the superclass.
  • Method overriding is closely tied to the concept of inheritance. It can only occur within a subclass that inherits from a superclass.
  • Python provides the super() keyword to call the overridden method from the superclass within the overriding method. This allows us to incorporate the behavior of the superclass method within the overriding method so that we do not lose the original functionality.
  • Method overriding enhances the code reusability. By defining a common method in the base class and then allowing derived classes to override it, we can prevent the code duplication across different subclasses.
  • Python supports multiple inheritance, which means a subclass can inherit from multiple superclasses. In such cases, method overriding allows the subclass to customize the behavior inherited from multiple superclasses by providing its own implementation.

Rules of Method Overriding in Python


There are the following certain important rules to override a method in Python. They are:

(1) Method overriding occurs only when inheritance is there. It can’t be performed within a class. We need to create a subclass from a superclass to perform method overriding.

(2) The overriding method in the subclass must have the same method name, the same parameters (including their types), and the same return type as the overridden method in the superclass. This ensures that the method signature remains the same.

(3) The overriding method cannot have reduced accessibility compared to the overridden method. In other words, if the overridden method in the superclass is public, the overriding method in the subclass must also be public.

(4) Only the instance method can be overridden in the subclass in Python.

(5) Methods decorated with the @staticmethod or @classmethod decorators are not meant for overriding. They belong to the class rather than to instances.

(6) Method overriding with multiple inheritance, the method resolution order (MRO) plays an important role in determining which method is invoked.

Method Overriding Example Programs


Let’s take some important example programs for the best practice based on the concept of method overriding in Python.

Overriding Methods of a Class

Example 1:

# Define a base class.
class A:
    # Overridden method
    def msg(self):
        print("msg-A")

# Define a derived class that inherits from its base class.
class B(A):
    # Overriding method
    def msg(self):
        print("msg-B")

# Outside the class definition.
# Create an object of class A.
a = A()
a.msg() # It will print the method of class A.

# Create an object of class B.
b = B()
b.msg() # It will print the method of class B.
Output:
       msg-A
       msg-B

Note: In method overriding, the Python interpreter determines which method implementation to execute based on the actual object’s type at runtime.

Example 2:

class A:
    def msg(self):
        print("msg-A")

class B(A):
    def msg(self):
        print("msg-B")

class C(A):
    def msg(self):
        print("msg-C")
a = A()
a.msg()

b = B()
b.msg()

c = C()
c.msg()
Output:
       msg-A
       msg-B
       msg-C

In this example, we have defined a class named A that contains an msg() method. This method displays a message. The derived classes B and C inherit from class A and override msg() method to provide their own implementation for displaying message.

Example 3:

# Real life example of method overriding in Python.
class Bank:
    def getroi(self):
        pass

class SBI(Bank):
    def getroi(self):
        return 7

class HDFC(Bank):
    def getroi(self):
        return 8

class BOI(Bank):
    def getroi(self):
        return 7.5

obj1 = SBI()
obj2 = HDFC()
obj3 = BOI()

print("SBI rate of interest: ", obj1.getroi())
print("HDFC rate of interest: ", obj2.getroi())
print("BOI rate of interest: ", obj3.getroi())
Output:
       SBI rate of interest:  7
       HDFC rate of interest:  8
       BOI rate of interest:  7.5

Method Overriding with Arguments

Let’s take an example program in which we will perform method overriding with arguments in Python.

Example 4:

# Calculation example
class Calculation:
    def calc(self, a, b):
        pass

class Addition(Calculation):
    def calc(self, a, b):
        s = a + b
        print("Sum: ", s)

class Subtraction(Calculation):
    def calc(self, a, b):
        s = a - b
        print("Sub: ", s)

class Multiplication(Calculation):
    def calc(self, a, b):
        m = a * b
        print("Multiply: ", m)

obj1 = Addition()
obj2 = Subtraction()
obj3 = Multiplication()
obj1.calc(20, 30)
obj2.calc(40, 10)
obj3.calc(10, 20)
Output:
       Sum:  50
       Sub:  30
       Multiply:  200

In this example, we have a base class named Calculation that contains a calc() method. This method takes two parameters named a and b. Three subclasses, Addition, Subtraction, and Multiplication inherit from the Calculation class and provide their own specific implementations of the calc method.

Each subclass overrides the calc() method with its own logic for addition, subtraction, and multiplication, respectively, to perform arithmetic operations. To override a method, the method name, parameters, and return type must remain the same in the subclasses as in its superclass.

Method Overriding with Multiple Inheritance

Like other programming languages such as C++, Python also supports multiple inheritance. When a class is inherited from more than one base class, it is called multiple inheritance. Let’s take examples based on the method overriding with multiple inheritance.

Example 5:

class Parent1:
    def display(self):
        print("Method-Parent1")

class Parent2:
    def show(self):
        print("Method-Parent2")

class Child(Parent1, Parent2):
    def display(self):
        print("Method-Child")

child = Child()
child.display()
child.show()
Output:
       Method-Child
       Method-Parent2

Example 6:

class Parent1:
    def display(self):
        print("Method-Parent1")

class Parent2:
    def display(self):
        print("Method-Parent2")

class Child(Parent1, Parent2):
    def display(self):
        print("Method-Child")

child = Child()
child.display()
Output:
      Method-Child

In this example, we have defined two classes named Parent1 and Parent2. Both classes contain a display() method with the same name. Then, we have defined a subclass named Child that inherits from both Parent1 and Parent2. The Child class also overrides the display() method, providing its own implementation.

After that, we have created an instance of the Child class and assigned to the child variable. When we call child.display(), the overriding method in the Child class is invoked, and displayed “Method-Child” on the console.

Example 7:

class A:
    def speak(self):
        print("Class A speaks.")

class B(A):
    def speak(self):
        print("Class B speaks.")

class C(A):
    def speak(self):
        print("Class C speaks.")

class D(B, C):
    pass

# Create an instance of class D
d = D()
# Call the overridden method
d.speak()
Output:
       Class B speaks.

In this example, we have four classes: A, B, C, and D. Both classes B and C inherit from class A, and class D inherits from both B and C classes. All classes have an overridden speak() method with the same name.

The order in which B and C are listed in the class definition of D (class D(B, C)) determines the method resolution order (MRO). In this case, class B is listed before class C, so class B takes precedence in the MRO.

When we create an instance of class D and call the speak() method, it calls the speak() method of class B. This is because it is the first class in the MRO that has the speak() method with its own implementation.

Method Overriding with Multilevel Inheritance

Let’s take an example based on the method overriding with multilevel inheritance in Python. We will override only one method of its parent classes.

Example 7:

class ClassA:
    def show(self):
        print("ClassA-method")

class ClassB(ClassA):
    def display(self):
        print("ClassB-method")

class ClassC(ClassB):
    def display(self):
        print("ClassC-method")

obj = ClassC()
obj.display()
obj.show()
Output:
       ClassC-method
       ClassA-method

Accessing Superclass Method with Overriding


In Python, we can also call the superclass overridden method inside the subclass overriding method. It allows us to extend the behavior of the superclass method within the overriding method. There are two ways to achieve this:

1. Using Class Name: We can access and call the overridden method from the superclass within the overriding method of the subclass. Let’s take an example.

Example 8:

class ClassA:
    def show(self):
        print("ClassA-method")

class ClassB(ClassA):
    def show(self):
      # Calling overridden method from the superclass using class name within overriding method of subclass.   
        ClassA.show(self)
        print("ClassB-method")

obj = ClassB()
obj.show()
Output:
        ClassA-method
        ClassB-method

2. Using Super Keyword: We can also use the super() function to access and call the overridden method from the superclass within the overriding method of the subclass.

Example 9:

class A:
    def msg(self):
        print("msg-A")

class B(A):
    def msg(self):
      # Calling superclass method using super keyword within the overriding method.
        super().msg()
        print("msg-B")

# Outside the class definition.
b = B()
b.msg()
Output:
       msg-A
       msg-B

In this example, we have used the super() keyword to call the overridden method from the superclass within the overriding method.

Advantages of Method Overriding


There are the following advantages of using method overriding in Python. They are as:

  • Method overriding is used to achieve runtime polymorphism in Python.
  • It is used to change the existing functionality or behavior of the superclass method.
  • Method overriding allows us to extend the functionality of a base class without altering its original implementation. We can add a new feature in the derived class.
  • By defining a common method in the base class and then allowing derived classes to override it, we can prevent the code duplication across different derived classes.
  • If you want the same method signature with different behaviors in the base class as well as derived class, you should use method overriding feature.

In this tutorial, we have discussed the method overriding in Python with lots of important example programs. Hope that you will have understood the basic rules of method overriding and practiced all programs. In the next, we will understand polymorphism in Python which is one of the most important object-oriented programming feature.
Thanks for reading!!!