What is Polymorphism?
Polymorphism means "many forms" - it allows objects of different types to be treated
uniformly through a common interface. The same method name can behave differently
based on the object type that calls it.
Real-World Analogy
Think of a universal remote control. The "play" button works the same way whether
you're controlling a TV, DVD player, or streaming device. Each device responds
differently to "play", but the interface (the button) remains consistent.
Three Types of Polymorphism
Method Overriding
Child classes provide specific implementations of parent methods
Method Overloading
Same method name with different parameters (limited in Python)
Duck Typing
"If it walks like a duck and quacks like a duck, it's a duck"
Essential Python Implementation
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
return f"{self.name} makes a sound"
def move(self):
return f"{self.name} moves"
class Dog(Animal):
def make_sound(self):
return f"{self.name} barks: Woof! Woof!"
def move(self):
return f"{self.name} runs on four legs"
class Cat(Animal):
def make_sound(self):
return f"{self.name} meows: Meow! Meow!"
def move(self):
return f"{self.name} prowls silently"
class Bird(Animal):
def make_sound(self):
return f"{self.name} chirps: Tweet! Tweet!"
def move(self):
return f"{self.name} flies through the air"
def animal_concert(animals):
print("Welcome to the Animal Concert!\n")
for animal in animals:
print(f"Sound: {animal.make_sound()}")
print(f"Movement: {animal.move()}")
print("-" * 40)
animals = [
Dog("Buddy"),
Cat("Whiskers"),
Bird("Tweety"),
Dog("Rex"),
Cat("Mittens")
]
animal_concert(animals)
class DataProcessor:
def process(self, data):
raise NotImplementedError("Subclasses must implement process method")
class JSONProcessor(DataProcessor):
def process(self, data):
import json
return json.dumps(data, indent=2)
class XMLProcessor(DataProcessor):
def process(self, data):
xml = "<data>\n"
for key, value in data.items():
xml += f" <{key}>{value}</{key}>\n"
xml += "</data>"
return xml
class CSVProcessor(DataProcessor):
def process(self, data):
headers = ",".join(data.keys())
values = ",".join(str(v) for v in data.values())
return f"{headers}\n{values}"
def export_data(processor, data):
return processor.process(data)
sample_data = { "name": "John Doe", "age": 30, "city": "New York" }
processors = [
JSONProcessor(),
XMLProcessor(),
CSVProcessor()
]
print("=== DATA PROCESSING POLYMORPHISM ===")
for processor in processors:
processor_name = processor.__class__.__name__
result = export_data(processor, sample_data)
print(f"\n{processor_name} Output:")
print(result)
Key Benefits of Polymorphism
- Flexibility: Write code that works with multiple object types
- Extensibility: Add new types without changing existing code
- Maintainability: Reduce code duplication and improve organization
- Interface Consistency: Same method names across different implementations
Key Insight
Polymorphism enables you to write functions that work with any object that implements
the expected interface. This makes your code more flexible and easier to extend.
Focus on consistent method names and signatures across related classes.