Polymorphism Techniques
Understanding Polymorphism in Python
Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables more flexible and extensible code design.
Types of Polymorphism
1. Method Overriding
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
## Polymorphic behavior
def animal_sound(animal):
animal.speak()
## Usage
dog = Dog()
cat = Cat()
animal_sound(dog) ## Outputs: Dog barks
animal_sound(cat) ## Outputs: Cat meows
2. Duck Typing Polymorphism
class Duck:
def swim(self):
print("Duck swimming")
class Boat:
def swim(self):
print("Boat floating")
def water_movement(obj):
obj.swim()
## Polymorphic behavior without inheritance
duck = Duck()
boat = Boat()
water_movement(duck) ## Outputs: Duck swimming
water_movement(boat) ## Outputs: Boat floating
Polymorphism Techniques
Technique |
Description |
Key Characteristic |
Method Overriding |
Redefine methods in child classes |
Inheritance-based |
Duck Typing |
Objects with similar methods |
Interface-like behavior |
Abstract Base Classes |
Define common interfaces |
Enforced method implementation |
3. Abstract Base Classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
Polymorphism Flow
graph TD
A[Base Class/Interface] --> B[Multiple Implementations]
B --> C[Polymorphic Method Calls]
C --> D[Dynamic Behavior]
Advanced Polymorphism Techniques
Multiple Dispatch
class MathOperations:
def add(self, x, y):
return x + y
def add(self, x, y, z):
return x + y + z
## Demonstrates method overloading-like behavior
math_ops = MathOperations()
print(math_ops.add(1, 2)) ## Two arguments
print(math_ops.add(1, 2, 3)) ## Three arguments
Best Practices
- Use polymorphism to create flexible designs
- Prefer composition over complex inheritance
- Implement abstract base classes for clear interfaces
- Keep polymorphic implementations simple and intuitive
LabEx encourages developers to explore polymorphism as a powerful object-oriented programming technique.