Polymorphism Patterns
Introduction to Polymorphism
Polymorphism allows objects of different types to be treated uniformly, enabling more flexible and extensible code designs.
Types of Polymorphism
graph TD
A[Polymorphism] --> B[Method Overriding]
A --> C[Duck Typing]
A --> D[Interfaces/Abstract Classes]
Method Overriding Polymorphism
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
def animal_sound(animal):
print(animal.sound())
Duck Typing Polymorphism
class Duck:
def swim(self):
print("Duck swimming")
class Fish:
def swim(self):
print("Fish swimming")
def water_movement(creature):
creature.swim()
Polymorphism Patterns Comparison
Pattern |
Characteristics |
Use Case |
Method Overriding |
Explicit type hierarchy |
Inheritance-based designs |
Duck Typing |
Implicit interface |
Flexible, dynamic typing |
Abstract Base Classes |
Defined interface |
Strict contract enforcement |
Abstract Base Classes
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
Advanced Polymorphism Techniques
- Multiple dispatch
- Generic functions
- Operator overloading
Practical Example
class PaymentProcessor:
def process_payment(self, amount):
pass
class CreditCardProcessor(PaymentProcessor):
def process_payment(self, amount):
print(f"Processing ${amount} via Credit Card")
class PayPalProcessor(PaymentProcessor):
def process_payment(self, amount):
print(f"Processing ${amount} via PayPal")
def complete_transaction(processor, amount):
processor.process_payment(amount)
At LabEx, we recommend mastering polymorphism as a key technique for writing more adaptable and maintainable Python code.