Introduction #
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables methods with the same name to behave differently depending on the object calling them, promoting flexibility and reusability in code.
1. Understanding Polymorphism #
Polymorphism allows you to define a single interface and have multiple implementations. It is often demonstrated through method overriding and method overloading.
Key Types of Polymorphism: #
- Compile-Time Polymorphism: Achieved using method overloading (limited in Python as it supports dynamic typing).
- Run-Time Polymorphism: Achieved using method overriding.
2. Polymorphism with Inheritance #
Example: #
class Animal:
def sound(self):
return "Some generic animal sound"
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
# Using polymorphism
animals = [Dog(), Cat(), Animal()]
for animal in animals:
print(animal.sound())
Output: #
Woof!
Meow!
Some generic animal sound
3. Polymorphism with Functions and Methods #
Example: #
A function can take any object as an argument and call the appropriate method based on the object type.
def make_sound(animal):
print(animal.sound())
class Dog:
def sound(self):
return "Woof!"
class Cat:
def sound(self):
return "Meow!"
dog = Dog()
cat = Cat()
make_sound(dog) # Output: Woof!
make_sound(cat) # Output: Meow!
4. Polymorphism in Built-In Functions #
Example: #
The len()
function works differently based on the type of the object passed.
print(len("Hello")) # Output: 5
print(len([1, 2, 3])) # Output: 3
print(len((1, 2, 3))) # Output: 3
5. Method Overriding in Polymorphism #
When a subclass provides a specific implementation of a method that is already defined in its superclass, it overrides the method.
Example: #
class Vehicle:
def start(self):
return "Starting vehicle..."
class Car(Vehicle):
def start(self):
return "Starting car..."
class Bike(Vehicle):
def start(self):
return "Starting bike..."
vehicles = [Car(), Bike(), Vehicle()]
for vehicle in vehicles:
print(vehicle.start())
Output: #
Starting car...
Starting bike...
Starting vehicle...
6. Operator Overloading in Polymorphism #
Python allows operators like +
, *
, etc., to be overloaded by defining special methods in a class.
Example: #
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print(v3) # Output: Vector(6, 8)
7. Abstract Classes and Polymorphism #
Abstract classes define methods that must be implemented by subclasses, ensuring a common interface.
Example: #
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(shape.area())
Output: #
78.5
24
8. Benefits of Polymorphism #
- Code Reusability: Reduces code duplication by allowing a single interface for different types.
- Flexibility: Easily extendable with new classes.
- Readability: Cleaner and more modular code.
9. Best Practices #
- Use meaningful method names to make polymorphism intuitive.
- Leverage abstract base classes for enforcing method implementation in subclasses.
- Avoid overcomplicating polymorphism; keep implementations simple and clear.
Conclusion #
Polymorphism in Python enhances the flexibility and scalability of programs by enabling multiple implementations of methods and operations. By understanding and using polymorphism effectively, developers can write cleaner, more modular, and reusable code.