Polymorphism Techniques
Understanding Polymorphism in Python
Polymorphism is a core concept in object-oriented programming that 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
graph TD
A[Polymorphism] --> B[Method Overriding]
A --> C[Duck Typing]
A --> D[Interfaces]
A --> E[Operator Overloading]
Method Polymorphism Example
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
class Duck(Animal):
def sound(self):
return "Quack!"
def animal_sound(animal):
print(animal.sound())
## Polymorphic behavior
animals = [Dog(), Cat(), Duck()]
for animal in animals:
animal_sound(animal)
Duck Typing Polymorphism
class FileWriter:
def write(self, data):
print(f"Writing to file: {data}")
class NetworkStream:
def write(self, data):
print(f"Sending over network: {data}")
def send_data(writer):
writer.write("Hello, World!")
## Different objects with same method interface
send_data(FileWriter())
send_data(NetworkStream())
Polymorphism Techniques Comparison
Technique |
Description |
Use Case |
Method Overriding |
Redefining methods in child classes |
Specialized behavior |
Duck Typing |
Focusing on object capabilities |
Flexible interfaces |
Operator Overloading |
Customizing operator behavior |
Custom object interactions |
Advanced Polymorphic Pattern
class Shape:
def area(self):
raise NotImplementedError("Subclass must implement abstract method")
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
def print_area(shape):
print(f"Area: {shape.area()}")
## Polymorphic behavior
shapes = [Rectangle(5, 3), Circle(4)]
for shape in shapes:
print_area(shape)
Operator Overloading 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})"
## Custom addition behavior
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3) ## Outputs: Vector(4, 6)
Best Practices
- Use polymorphism to create more flexible code
- Implement consistent interfaces
- Avoid deep inheritance hierarchies
At LabEx, we recommend mastering polymorphism to write more dynamic and adaptable Python applications.
Key Takeaways
- Polymorphism enables flexible object interactions
- Multiple techniques exist for implementing polymorphic behavior
- Understanding context helps choose the right approach