Polymorphism and Method Overriding
Overview
Polymorphism lets different classes respond to the same function call in unique ways. You'll see how method overriding allows subclasses to redefine inherited methods for customized behavior, enabling flexible and extensible code design.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Polymorphism: Understand what polymorphism is and how it works in Python.
- Method overriding: Learn how to override parent methods in subclasses.
- Same interface, different behavior: Discover how different classes can respond to the same method call differently.
- Practical applications: See how polymorphism makes code flexible and extensible.
Why This Matters
Polymorphism is one of the most powerful OOP concepts! It lets you write code that works with different types of objects in the same way, even though each object behaves differently. Think of it like a universal remote - you press the same button (call the same method), but different devices (different classes) respond in their own way. This makes your code flexible, extensible, and easier to maintain!
Step 1: What is Polymorphism?
Polymorphism means "many forms" - different classes can respond to the same method call in different ways:
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# Same method call, different behaviors
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak()) # "Woof!" then "Meow!"
Same Method Name
Different classes can have methods with the same name. When you call that method, each class responds in its own way!
Different Implementations
Each class implements the method differently. Dog's speak() returns "Woof!", Cat's returns "Meow!"
Unified Interface
You can treat different objects the same way - call speak() on any animal, and it responds appropriately!
Key Concept: Polymorphism is like having a universal "play" button. When you press play on a music player, it plays music. When you press play on a video player, it plays video. Same button, different behavior - that's polymorphism!
Mini Practice #1: Polymorphism
Try It YourselfCreate multiple classes with the same method:
What happened? Both Rectangle and Circle have an area() method, but they calculate area differently! When you call shape.area() on each object, Python automatically uses the correct implementation. This is polymorphism - same method name, different behavior!
Step 2: Method Overriding
Method overriding happens when a subclass redefines a method from the parent class:
class Vehicle:
def start(self):
return "Vehicle starts"
class Car(Vehicle):
def start(self): # Override parent method
return "Car engine starts"
class Bike(Vehicle):
def start(self): # Override parent method
return "Bike pedals start"
car = Car()
bike = Bike()
print(car.start()) # "Car engine starts"
print(bike.start()) # "Bike pedals start"
Parent Defines Method
The parent class defines a method with a default implementation. This provides a fallback behavior.
Subclass Overrides
The subclass defines the same method name with its own implementation. This replaces the parent's version!
Subclass Version Used
When you call the method on a subclass object, Python uses the subclass's version, not the parent's!
Why Override?
Method overriding lets you customize behavior for specific subclasses while keeping a consistent interface. All vehicles can start, but cars and bikes start differently. Overriding lets each subclass implement its own version!
Step 3: Polymorphism in Action
Polymorphism shines when you work with multiple objects of different types:
class Employee:
def calculate_pay(self):
return 0
class FullTime(Employee):
def calculate_pay(self):
return 5000
class PartTime(Employee):
def calculate_pay(self):
return 2500
employees = [FullTime(), PartTime(), FullTime()]
total = sum(emp.calculate_pay() for emp in employees)
print(f"Total payroll: ${total}") # $12500
Remember: Polymorphism lets you write code that works with different types without knowing the specific type! You can call calculate_pay() on any employee, and each type calculates it correctly. This makes your code flexible and easy to extend!
Mini Practice #2: Polymorphism with Lists
Try It YourselfUse polymorphism with a list of different objects:
What happened? You created a list containing different types of animals (Dog, Cat, Bird). When you loop through and call make_sound() on each, Python automatically uses the correct implementation for each type! This is polymorphism - one interface, many forms!
End-of-Lesson Exercises
Exercise 1: Method Overriding
Create a parent class Shape with method draw(self) that returns "Drawing shape". Create a subclass Circle that overrides draw to return "Drawing circle". Create a Circle object and call draw().
Define class Shape with draw method, create Circle(Shape) that overrides draw, create Circle object, call draw.
Exercise 2: Polymorphism
Create a parent class Payment with method process(self) that returns "Processing payment". Create subclasses CreditCard and PayPal that override process to return "Processing credit card" and "Processing PayPal" respectively. Create a list with one of each and call process() on each.
Define class Payment with process method, create CreditCard and PayPal subclasses that override process, create list, loop and call process.