Abstract smoke background

Understanding Method Overriding in Python with area() Example

Introduction

n object-oriented programming, method overriding is a powerful feature that allows a subclass to modify or extend the behavior of a method inherited from its parent class. Python supports this feature naturally, enabling more flexible and dynamic code. This blog post explains method overriding with a practical example: overriding the area() method in a Rectangle subclass that inherits from a base class Shape.

Master Python: 600+ Real Coding Interview Questions
Master Python: 600+ Real Coding Interview Questions

Middle: How Method Overriding Works in Python

To understand method overriding, let’s start by defining a base class Shape. This class will contain a generic method area(), which we’ll later override in the subclass Rectangle.

class Shape:
def area(self):
return "Area is not defined for Shape"

Machine Learning & Data Science 600+ Real Interview Questions
Machine Learning & Data Science 600 Real Interview Questions

Now, we create a subclass Rectangle that inherits from Shape and provides its own implementation of the area() method:

class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

In this example, the Rectangle class overrides the area() method. If we create an object of Rectangle and call the area() method, Python will automatically use the overridden version in the subclass, not the one in Shape.

rect = Rectangle(5, 4)
(rect.area()) # Output: 20

This behavior is known as dynamic polymorphism, where the method that gets called is determined at runtime based on the object’s actual class—not the reference type. Even if we store the object in a variable typed as Shape, the overridden method in Rectangle will be called:

shape_obj = Rectangle(6, 3)
(shape_obj.area()) # Output: 18

Master LLM and Gen AI: 600+ Real Interview Questions
Master LLM and Gen AI: 600+ Real Interview Questions

Conclusion

Method overriding in Python is essential for creating flexible, reusable, and dynamic class hierarchies. By allowing subclasses to define their own behavior for methods inherited from a parent class, Python empowers developers to write cleaner and more intuitive code. The Rectangle example clearly demonstrates how overriding the area() method helps implement class-specific logic while adhering to the principle of polymorphism. In short, method overriding isn’t just a feature—it’s a foundation of smart object-oriented design.

























Leave a Reply