Method Overriding in Python: How It Works and Why You Need It
Updated on Dec 05, 2024 | 16 min read | 43.6k views
Share:
For working professionals
For fresh graduates
More
Updated on Dec 05, 2024 | 16 min read | 43.6k views
Share:
Table of Contents
Did you know that Python powers some of the most innovative technologies today and holds a staggering 29.1% market share in the programming world? Whether you're an aspiring developer or a seasoned professional, mastering method overriding in Python is a game-changer.
In object-oriented programming (OOP), classes are thought of as blueprints and objects as the actual buildings made from them. But here’s the twist: inheritance lets subclasses inherit behaviors from parent classes, and method overriding lets you tweak those behaviors to fit your needs. This flexibility makes Python one of the most dynamic and powerful programming languages out there.
In this blog, you will explore method overriding in Python — from what it is and how it works to why it’s essential for creating efficient and future-proof software. Ready to take your Python skills to the next level?
Let’s dive in!
Method overriding in Python allows a subclass to provide a specific implementation of a method already defined in its parent class. This core concept in Object-Oriented Programming (OOP) makes your code more flexible and customizable.
When you use method overriding, you redefine a method in the subclass with the same name and parameters as the one in the parent class. This enables you to change the method's behavior in the subclass while preserving the parent class's structure.
The key features of method overriding in Python include:
But why is it such a powerful tool in object-oriented programming (OOP)? Read ahead!
While it allows you to change the behavior of methods in subclasses, the actual value of method overriding becomes clear when we look at its purpose in real-world programming.
Let’s understand its vital purpose:
In short, method overriding in Python is all about providing customized real-world solutions, ensuring your code is adaptable, and avoiding redundancy.
Also Read: 12 Amazing Real-World Applications of Python
Imagine you're working on a project that involves multiple types of vehicles — cars, trucks, and motorcycles. Each can "drive" but has unique driving behaviors. Instead of rewriting the logic for each vehicle from scratch, you can use method overriding to customize the behavior of the drive() method for each while maintaining a shared interface.
This is exactly how method overriding in Python works: a subclass inherits a method from its parent class and then provides its implementation, adapting it for its specific needs.
Let’s understand it with an example along with its output:
Consider the following code where we have a parent class, Vehicle, and two subclasses, Car and Truck, each overriding the drive() method to provide their specific implementations.
# Parent class
class Vehicle:
def drive(self):
print("This vehicle is driving.")
# Child class 1: Car
class Car(Vehicle):
def drive(self):
print("The car is driving on the road.")
# Child class 2: Truck
class Truck(Vehicle):
def drive(self):
print("The truck is hauling cargo on the highway.")
# Instantiate objects
car = Car()
truck = Truck()
# Calling the overridden methods
car.drive() # Output: The car is driving on the road.
truck.drive() # Output: The truck is hauling cargo on the highway.
Now that we’ve seen an example, let's take a closer look at how method overriding happens in Python.
The process involves a few straightforward steps:
1. Define a parent class with a method: The parent class defines a method, like drive(), with general behavior for all vehicles.
2. Create a child class that inherits from the parent class: The child classes, such as Car and Truck, inherit the properties and methods of the parent class Vehicle.
3. Redefine the method in the child class: The child class provides its version of the drive() method, overriding the one in the parent class.
Here’s a simple example of method overriding where a parent class Shape has a method area(), and the child classes Circle and Rectangle override it to calculate their respective areas:
# Parent class
class Shape:
def area(self):
pass # Placeholder for area method
# Child class 1: Circle
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
# Child class 2: Rectangle
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
# Instantiate objects
circle = Circle(5)
rectangle = Rectangle(4, 6)
# Calling the overridden methods
print(f"Area of Circle: {circle.area()}") # Output: Area of Circle: 78.5
print(f"Area of Rectangle: {rectangle.area()}") # Output: Area of Rectangle: 24
Now, let us move on to the key concepts of the method.
In Python, the super() function allows you to access methods from the parent class even when overridden in the child class. This can be useful when calling the parent class method inside the overridden method.
Here’s an example of how super() works with method overriding:
# Parent class
class Animal:
def sound(self):
print("Some generic animal sound")
# Child class 1: Dog
class Dog(Animal):
def sound(self):
super().sound() # Calling the parent class method
print("Bark")
# Child class 2: Cat
class Cat(Animal):
def sound(self):
super().sound() # Calling the parent class method
print("Meow")
# Instantiate objects
dog = Dog()
cat = Cat()
# Calling the overridden methods
dog.sound() # Output: Some generic animal sound \n Bark
cat.sound() # Output: Some generic animal sound \n Meow
In this example:
Now, as you understand the method overriding, knowing when to use it is just as important as knowing how to implement it. Below are a few scenarios:
So you've seen what method overriding in Python is, but what about method overloading? While both techniques sound similar, they serve different purposes.
Let’s unravel the difference between these two!
Method overloading typically occurs in statically typed languages like Java or C++, where multiple methods with the same name but different parameters can be defined.
However, in Python, method overloading is not natively supported, and it is simulated using default arguments or variable-length argument lists. Let’s compare the two in a clear, side-by-side table:
Aspects | Method Overloading | Method Overriding |
Implementation | Achieved via default arguments or variable-length argument lists. | Achieved by redefining a parent class method in the subclass. |
Time of Implementation | Not supported directly; simulated at runtime. | Occurs during runtime, when the subclass overrides the parent method. |
Syntax | Same method name, different parameters. | Same method name and parameters as the parent class. |
Return Type | Python doesn’t restrict return types; can vary with arguments. | The return type must be consistent with the parent class method. |
Static Method | Not applicable in Python for overloading. | Static methods can be overridden, but the method must be referenced through the class. |
Private and Final Methods | Overloading doesn’t apply to private or final methods in Python. | Private or final methods cannot be overridden unless the access modifiers are altered. |
Thus, understanding these distinctions is crucial for writing more efficient and maintainable Python code!
Also Read: Top 10 Reasons Why Python is So Popular With Developers in 2025
Inheritance is one of the cornerstones of Object-Oriented Programming (OOP). It allows one class to inherit properties and methods from another, fostering reusability, maintainability, and a hierarchical relationship between classes.
But what happens when we combine multiple inheritance or extend a class over several levels? The dynamic nature of method overriding becomes even more powerful and flexible in such scenarios.
Before we jump into method overriding in the context of multiple and multi-level inheritance, let’s first understand how inheritance works in Python.
At its core, inheritance in Python allows a class (called the child or subclass) to inherit attributes and methods from another class (called the parent or superclass). This reduces the need for repetitive code.
The power of method overriding in inheritance lies in how subclasses can change (override) inherited methods to suit their specific behavior while maintaining the structure defined by the parent class.
Also Read: Types of Inheritance in Python | Python Inheritance [With Examples]
Let’s see how method overriding works in both multiple and multi-level inheritance.
A class can inherit from multiple parent classes in multiple inheritance. This allows a child class to inherit features from multiple classes and override methods from all parent classes.
However, Python follows the Method Resolution Order (MRO) to determine which method to call when multiple parent classes have a method with the same name. Let’s look at an example:
# Parent Class 1
class Animal:
def sound(self):
print("Animal makes a sound")
# Parent Class 2
class Bird:
def sound(self):
print("Bird chirps")
# Child Class
class Parrot(Animal, Bird):
def sound(self):
print("Parrot squawks")
# Instantiate object
parrot = Parrot()
parrot.sound() # Output: Parrot squawks
In the example above:
Python uses the MRO to decide which method to execute, but in this case, the child class explicitly overrides the method.
In multilevel inheritance, a class inherits from another class, which in turn inherits from another class, forming a chain of inheritance. This adds another layer of complexity but also provides a powerful mechanism for modifying and extending inherited functionality.
Let’s look at how method overriding works in a multilevel inheritance hierarchy.
# Grandparent Class
class Animal:
def sound(self):
print("Animal makes a sound")
# Parent Class
class Mammal(Animal):
def sound(self):
print("Mammal makes a sound")
# Child Class
class Dog(Mammal):
def sound(self):
print("Dog barks")
# Instantiate object
dog = Dog()
dog.sound() # Output: Dog barks
In the example:
Thus, when combined with method overriding, both multiple inheritance and multilevel inheritance give you the power to write more dynamic and flexible Python code.
Also, for fun practice, read Perfect Number Program In Python: How to check if a number is perfect or not?
When you override a method in Python, there are situations where you might still want to call the parent class's version of the method — either before or after executing the custom behavior in the child class.
There are two common ways to achieve this in Python:
Both approaches give you the flexibility to call the parent class's method while allowing you to modify or extend it in the child class. Let's explore both in detail.
One straightforward method is to reference the parent class directly by its name. This is useful when you specify the method you want to call explicitly and know the exact class in the inheritance chain.
Let us grab it with an example:
# Parent Class
class Animal:
def sound(self):
print("Some generic animal sound")
# Child Class
class Dog(Animal):
def sound(self):
Animal.sound(self) # Calling the parent class method explicitly
print("Dog barks")
# Instantiate object
dog = Dog()
dog.sound()
Output:
Some generic animal sound
Dog barks
In this example:
The super() function automatically handles the complexity of MRO in the case of multiple inheritance. This makes it ideal for scenarios where you have numerous parent classes or work with more complex class hierarchies.
Here’s a code example for it:
# Parent Class
class Animal:
def sound(self):
print("Some generic animal sound")
# Child Class 1
class Mammal(Animal):
def sound(self):
super().sound() # Calls the parent class method using super()
print("Mammal makes a sound")
# Child Class 2
class Dog(Mammal):
def sound(self):
super().sound() # Calls the method from the Mammal class
print("Dog barks")
# Instantiate object
dog = Dog()
dog.sound()
Output:
Some generic animal sound
Mammal makes a sound
Dog barks
In this example:
Also Read: Difference Between Function and Method in Python
Now that we've explored how to call parent methods within overridden methods let's dive into a more nuanced aspect— overriding methods with different parameters.
upGrad’s Exclusive Data Science Webinar for you –
Transformation & Opportunities in Analytics & Insights
Sometimes, you might need to modify the way parameters are handled, especially when you want to pass a varying number of arguments or want to make certain parameters optional.
Overriding methods with different parameters offers great flexibility in customizing inherited methods. Let’s look at three common approaches of it:
With *args, we can pass any number of positional arguments to a method. This is useful when you don’t know how many arguments might be passed to the method, allowing for flexibility.
Example:
# Parent Class
class Animal:
def speak(self, *args):
for sound in args:
print(f"Animal makes a {sound} sound")
# Child Class
class Dog(Animal):
def speak(self, *args):
print("Dog says:")
super().speak(*args) # Calls parent class speak method with *args
print("Woof!")
# Instantiate object
dog = Dog()
dog.speak("bark", "growl")
Output:
Dog says:
Animal makes a bark sound
Animal makes a growl sound
Woof!
**kwargs allows you to pass a variable number of keyword arguments to a method. It’s useful to pass named arguments to a method without specifying them upfront.
Example:
# Parent Class
class Animal:
def move(self, **kwargs):
print(f"Animal is moving {kwargs.get('direction', 'forward')}")
# Child Class
class Dog(Animal):
def move(self, **kwargs):
print("Dog is moving:")
super().move(**kwargs) # Calls parent class move method with **kwargs
print(f"Dog is moving {kwargs.get('direction', 'forward')} with speed {kwargs.get('speed', 'normal')}")
# Instantiate object
dog = Dog()
dog.move(direction="left", speed="fast")
Output:
Dog is moving:
Animal is moving left
Dog is moving left with speed fast
You can also override methods with parameters that have default values, making them optional when calling the method. This allows you to provide a more flexible interface while keeping the method signature clean.
Example:
# Parent Class
class Animal:
def info(self, name="Unknown", age=0):
print(f"Animal's name is {name} and age is {age}")
# Child Class
class Dog(Animal):
def info(self, name="Unknown", age=0, breed="Unknown"):
super().info(name, age) # Calls parent class info method
print(f"Dog's breed is {breed}")
# Instantiate object
dog = Dog()
dog.info("Buddy", 3, "Labrador")
Output:
Animal's name is Buddy and age is 3
Dog's breed is Labrador
These techniques help you customize method behavior in child classes while maintaining flexibility in their acceptable parameters.
Method overriding is like the customization tool of object-oriented programming. It allows you to redefine a pre-existing method from a parent class into a child class to suit your needs better.
This flexibility makes Python a powerful language for building scalable and reusable code. Have a look at the key features of it:
In data science, where flexibility and customization are key, method overriding is a game-changer. It helps you tailor methods to specific data preprocessing, model training, and evaluation tasks.
Also Read: 5 Reasons to Choose Python for Data Science – How Easy Is It
Now that you understand what method overriding is and how it works, let's explore the real-world advantages it brings to the table.
Why stick to static, repetitive code when you can make it flexible, reusable, and scalable? Method overriding in Python isn’t just a feature — it’s a strategic tool that boosts your coding efficiency and adaptability.
Let’s break down how it benefits you as a developer.
In a nutshell, method overriding empowers your Python program code to be more dynamic, flexible, and efficient.
Also Read: Top 30 Python Pattern Programs You Must Know About
In today’s competitive world, upskilling is the key to standing out — and upGrad is at the forefront of offering hands-on training, real-world projects, and free courses to help you achieve career excellence.
Coding is at the core of upGrad's career-driven programs. The platform offers a range of Python courses focusing on practical, real-world applications, ensuring students learn by doing.
Some of the top courses include:
upGrad also offers free counseling sessions with experts who can help you choose the right course for your career goals.
So, book your counseling session today and take the first step towards building your career with Python!
Transform your career with our Popular Data Science Courses, offering in-depth training in data analysis, predictive modeling, and AI. Learn from industry leaders and work on practical projects to build the skills employers seek!
Boost your career with essential data science skills such as Python programming, statistical analysis, and AI modeling. Learn to turn raw data into actionable insights with industry-relevant tools and techniques!
References:
https://www.techspot.com/news/105157-python-most-popular-coding-language-but-challengers-gaining.html
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources