Introduction

Polymorphism is a fundamental concept in Python's Object-Oriented Programming (OOP) paradigm. It allows objects of different classes to be treated as objects of a common superclass. In this guide, we'll explore the concept of polymorphism and how to override methods in Python, along with sample code.


What Is Polymorphism?

Polymorphism is the ability of different classes to be treated as instances of a common base class. It allows objects to respond to methods in a way that is appropriate for their specific class. Polymorphism is achieved through method overriding, where a subclass provides a specific implementation for a method defined in the base class.


Defining a Base Class

To demonstrate polymorphism, we'll start by defining a base class with a method. Here's an example of a simple "Shape" class with a method called area():

# Defining a base class
class Shape:
def area(self):
pass # Placeholder method

Overriding a Method

To achieve polymorphism, you create subclasses that inherit from the base class and provide their own implementation for the method. Here's an example of a "Circle" subclass that overrides the area() method:

# Creating a subclass and overriding a method
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159265359 * self.radius ** 2

Polymorphic Behavior

Now, you can create objects of different classes (subclasses) and treat them as instances of the common base class. They will respond to the area() method differently based on their specific implementations.

# Creating objects of different classes
circle = Circle(5)
shapes = [circle]
# Polymorphic behavior
for shape in shapes:
print(f"Area: {shape.area()}")

Conclusion

Polymorphism and method overriding are powerful tools in Python's Object-Oriented Programming. They allow you to create a common interface for different classes, enabling more flexible and organized code. Understanding polymorphism is essential for building complex class hierarchies and achieving code reusability.