Polymorphism Mastery

Learn to use the same interface for different implementations

Essential Concept #3
1
2
3
4

🎯 80/20 Focus: What Really Matters

Master these 3 polymorphism patterns and you'll handle 80% of real-world scenarios: Method overriding, Duck typing, and Interface consistency

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: """ Base class defining the common interface """ def __init__(self, name): self.name = name def make_sound(self): """Base method to be overridden by subclasses""" return f"{self.name} makes a sound" def move(self): """Another method for polymorphic behavior""" return f"{self.name} moves" class Dog(Animal): """ Dog implementation with specific behavior """ def make_sound(self): """Override with dog-specific sound""" return f"{self.name} barks: Woof! Woof!" def move(self): """Override with dog-specific movement""" return f"{self.name} runs on four legs" class Cat(Animal): """ Cat implementation with different behaviors """ def make_sound(self): """Override with cat-specific sound""" return f"{self.name} meows: Meow! Meow!" def move(self): """Override with cat-specific movement""" return f"{self.name} prowls silently" class Bird(Animal): """ Bird implementation with unique behaviors """ def make_sound(self): """Override with bird-specific sound""" return f"{self.name} chirps: Tweet! Tweet!" def move(self): """Override with bird-specific movement""" return f"{self.name} flies through the air" # Polymorphism in action def animal_concert(animals): """ This function demonstrates polymorphism: Same method calls, different behaviors based on object type """ print("Welcome to the Animal Concert!\n") for animal in animals: # Same interface, different implementations print(f"Sound: {animal.make_sound()}") print(f"Movement: {animal.move()}") print("-" * 40) # Create different animal objects animals = [ Dog("Buddy"), Cat("Whiskers"), Bird("Tweety"), Dog("Rex"), Cat("Mittens") ] # Polymorphism: treat all animals the same way animal_concert(animals) # Advanced Polymorphism Example: Different data processors class DataProcessor: """ Base class for data processing """ def process(self, data): """To be overridden by subclasses""" raise NotImplementedError("Subclasses must implement process method") class JSONProcessor(DataProcessor): """ Process data as JSON """ def process(self, data): import json return json.dumps(data, indent=2) class XMLProcessor(DataProcessor): """ Process data as XML """ 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): """ Process data as CSV """ def process(self, data): headers = ",".join(data.keys()) values = ",".join(str(v) for v in data.values()) return f"{headers}\n{values}" # Polymorphic function works with any DataProcessor def export_data(processor, data): """ Polymorphic function: same interface (process method), different outputs """ return processor.process(data) # Sample data sample_data = { "name": "John Doe", "age": 30, "city": "New York" } # Polymorphism: same function call, different results 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.