Polymorphism
Polymorphism
Different classes can use the same method name in their own way.
This idea is called polymorphism.
The word means “many forms”.
What Is Polymorphism?
Polymorphism means one method name can behave differently depending on the object.
Why It Matters
It helps you:
- write flexible code
- reuse method names
- work with different object types
- keep programs clean
Real Example
A dog and a cat can both make a sound.
But the sound is different.
- Dog → Woof
- Cat → Meow
Both can use a method named sound().
Example
class Dog:
def sound(self):
print("Woof")
class Cat:
def sound(self):
print("Meow")
dog = Dog()
cat = Cat()
dog.sound()
cat.sound()
Output
Woof
Meow
Same method name, different behavior.
Use in a Loop
animals = [Dog(), Cat()]
for animal in animals:
animal.sound()
Output
Woof
Meow
The loop does not need to know the exact class.
Another Example
class Car:
def move(self):
print("Driving")
class Plane:
def move(self):
print("Flying")
items = [Car(), Plane()]
for item in items:
item.move()
Output
Driving
Flying
Polymorphism with Inheritance
Child classes can replace a parent method.
class Animal:
def sound(self):
print("Sound")
class Dog(Animal):
def sound(self):
print("Woof")
class Cat(Animal):
def sound(self):
print("Meow")
pets = [Dog(), Cat()]
for pet in pets:
pet.sound()
Output
Woof
Meow
Why This Is Powerful
You can write one loop or function that works with many object types.
Code Along
Create classes:
TeacherStudent
Both should have method role() with different outputs.
Mini Challenge
Create classes:
CreditCardCash
Both should have method pay().
Outputs:
Paid by card
Paid by cash
Use a list and loop through both objects.
Real World Use Case
Apps use polymorphism for payments, notifications, vehicles, game actions, and user roles.
Quiz
- What is polymorphism?
- Can two classes use the same method name?
- Why is polymorphism useful?
- How does a loop use polymorphism?
Assignment
Create classes Bird and Fish with method move() and print both actions.
Summary
You learned that polymorphism lets different classes use the same method name with different behavior.