Introduction
In the previous lesson, you learned about encapsulation:
- Objects protect their internal data
- Interaction happens through methods
Polymorphism builds directly on this idea.
Polymorphism means:
- Different objects respond to the same method name
- The behaviour depends on the object’s class
- The code using the object does not need to know its type
In this lesson, you will learn how:
- Inheritance enables polymorphism
- Overridden methods create different behaviour
- One interface can work with many object types
Polymorphism in Simple Terms
If two objects both have a method called describe(), Python does not care what class they belong to.
It only cares that the method exists.
Example: Animals Speaking
class Animal:
def speak(self):
print("The animal makes a sound")
class Dog(Animal):
def speak(self):
print("Woof")
class Cat(Animal):
def speak(self):
print("Meow")
All three classes share the same method name:
speak()
But each behaves differently.
Predict:
What do you think will be printed?
class Animal:
def speak(self):
print("The animal makes a sound")
class Dog(Animal):
def speak(self):
print("Woof")
class Cat(Animal):
def speak(self):
print("Meow")
animals = [Dog(), Cat(), Animal()]
for animal in animals:
animal.speak()
Think about:
- Does Python check the object’s class?
- Or does it just call the method?
Run:
Run the program below to check your prediction.
Why This Is Useful
Without polymorphism, you might write code like this:
if type == "dog":
print("Woof")
elif type == "cat":
print("Meow")
With polymorphism:
- No
ifstatements needed - Code is easier to extend
- New classes can be added without changing existing code
Investigate:
Let’s use polymorphism with a more practical example.
Try this:
- Create a list containing different account types
- Call the same method on each object
Think about:
- Why does this work without checking the class type?
- How would adding a new account type affect the loop?
Modify:
The following program is meant to demonstrate polymorphism but contains an issue.
Fix the code so that each object responds correctly.
The problem
- The overridden method is missing
self