Table of contents
1.
Introduction
2.
Method Overriding in Python
3.
Method Overriding with Multiple & Multilevel Inheritance
4.
Multiple Inheritance
4.1.
Python
5.
Multilevel Inheritance
5.1.
Python
6.
Calling the Parent's Method Within the Overridden Method
6.1.
Python
7.
Frequently Asked Questions
7.1.
Can a method in a child class have the same name as a method in the parent class?
7.2.
What happens if I forget to use super() in an overridden method?
7.3.
Is it possible to override a method in Python but keep the original functionality?
7.4.
What is the difference between overloading and overriding?
8.
Conclusion
Last Updated: Aug 21, 2024
Easy

Method Overriding in Python

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Method overriding is a fundamental concept in object-oriented programming, allowing us to tweak or extend how inherited methods work. In Python, this feature plays a pivotal role in making code more modular & reusable. 

Method Overriding in Python

By understanding method overriding, you'll unlock new possibilities in managing & organizing code, especially when working with complex inheritance structures. In this article we are going to learn about everything related to method overriding in Python

Method Overriding in Python

Method overriding in Python allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This is achieved by defining a method in the subclass with the same name as the method in the superclass. When the subclass method is called, it overrides the superclass method, enabling customized behavior. This technique supports polymorphism, allowing objects of the subclass to behave differently from those of the superclass, while still adhering to the same interface.

Method Overriding with Multiple & Multilevel Inheritance

When we talk about method overriding in Python, it's all about giving new powers or changing the behavior of methods in subclasses that are inherited from a parent class. This gets even more interesting when we deal with multiple & multilevel inheritance, where a class might inherit from more than one parent class or through multiple levels.

Multiple Inheritance

Multiple inheritance is when a class is derived from more than one base class. Imagine you have two classes, ClassA and ClassB, each with its own method myMethod(). If you create a new class, say ClassC, that inherits from both ClassA and ClassB, and you decide to override myMethod() in ClassC, you're customizing how ClassC responds to myMethod() calls. Here's a simple example to illustrate this:

  • Python

Python

class ClassA:

def myMethod(self):

print("Method in ClassA")

class ClassB:

def myMethod(self):

print("Method in ClassB")

class ClassC(ClassA, ClassB):

def myMethod(self):

print("Overridden method in ClassC")
# Creating an instance of ClassC

obj = ClassC()

obj.myMethod() # This will print: Overridden method in ClassC
You can also try this code with Online Python Compiler
Run Code

Output

Overridden method in ClassC


In this code, ClassC overrides myMethod(), so when we call myMethod() on an instance of ClassC, it executes the overridden method in ClassC, not the ones in ClassA or ClassB.

Multilevel Inheritance

Multilevel inheritance refers to a scenario where a class is derived from another derived class, creating a "chain" or "hierarchy" of inheritance. For example, if ClassB inherits from ClassA, and ClassC inherits from ClassB, that's multilevel inheritance. Overriding a method in ClassC affects how instances of ClassC respond to that method, but it doesn't change the behavior of ClassA or ClassB. Here's a simple demonstration:

  • Python

Python

class ClassA:

def myMethod(self):

print("Method in ClassA")

class ClassB(ClassA):

def myMethod(self):

print("Overridden method in ClassB")

class ClassC(ClassB):

def myMethod(self):

print("Further overridden method in ClassC")

# Creating an instance of ClassC

obj = ClassC()

obj.myMethod() # This will print: Further overridden method in ClassC
You can also try this code with Online Python Compiler
Run Code

Output

Further overridden method in ClassC

 

In ClassC, myMethod() is overridden to provide a new message. When we call myMethod() on an instance of ClassC, it uses the version of myMethod() defined in ClassC, not in ClassA or ClassB.

Calling the Parent's Method Within the Overridden Method

Sometimes when we override a method, we might still want to keep part of the original behavior from the parent class. This is where calling the parent's method within the overridden method comes into play. It's like saying, "I want to add some new steps, but let's not forget the original ones."

In Python, we can do this by using the super() function. This function helps us access methods from the parent class even after we've overridden them in a subclass. Let's see how this works with a simple example:

  • Python

Python

class Parent:

   def show(self):

       print("This is the parent method.")

class Child(Parent):

   def show(self):

       # Call the parent's show method first

       super().show()

       # Now add some additional behavior

       print("This is the overridden method in the child.")

# Create an instance of Child

child_obj = Child()

child_obj.show()
You can also try this code with Online Python Compiler
Run Code

Output

This is the parent method.
This is the overridden method in the child.


First, it calls the show() method from the Parent class, printing "This is the parent method." Then, it continues with the additional behavior defined in the Child class, printing "This is the overridden method in the child."

Frequently Asked Questions

Can a method in a child class have the same name as a method in the parent class?

Yes, a child class can have a method with the same name as one in the parent class. This is known as method overriding. The method in the child class will be used when called on an instance of the child class, allowing for customized behavior.

What happens if I forget to use super() in an overridden method?

If you don't use super() in an overridden method, the parent class's method won't be called. This might be okay if you intend to completely replace the parent's method, but if you need to retain the original behavior and build upon it, you should use super().

Is it possible to override a method in Python but keep the original functionality?

Yes, you can override a method and still keep its original functionality by calling the overridden method using super(). This allows you to add to the method's behavior rather than completely replacing it.

What is the difference between overloading and overriding?

Overloading involves defining multiple methods with the same name but different parameters in the same class, allowing different behaviors based on arguments. Overriding involves redefining a method in a subclass with the same name as in the superclass, providing specific behavior.

Conclusion

In this article, we learned about the concept of method overriding in Python, highlighting its significance in object-oriented programming. We've explored how to effectively use method overriding in scenarios involving multiple and multilevel inheritance, ensuring a clear understanding of how classes can inherit and customize behaviors from parent classes. Moreover, we learned the importance of invoking a parent's method within an overridden method using super(), allowing for an extension of functionality while retaining the foundational behavior.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass