Python Polymorphism - Same Thing, Different Behavior
What is Polymorphism?
Polymorphism means “many forms.”
It’s a concept where something (like a function or method) behaves differently based on the object it is working with.
Imagine this: A person can be a student, a player, and a singer. Same person — but different roles. That’s the idea behind polymorphism.
Simple Example 1: len() Function
Python has a built-in function len()
that gives you the length of something.
print(len("hello")) # Length of a string
print(len([1, 2, 3, 4])) # Length of a list
print(len((10, 20))) # Length of a tuple
5
4
2
Why This Output?
"hello"
has 5 letters →len("hello")
is 5[1, 2, 3, 4]
has 4 items →len([1, 2, 3, 4])
is 4(10, 20)
has 2 items →len((10, 20))
is 2
The same function (len()
) gives correct results for different types — that’s polymorphism!
Simple Example 2: Polymorphism with Classes
Let’s look at how polymorphism works with objects from different classes.
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
# Using polymorphism
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak())
Woof!
Meow!
Why This Output?
- Both
Dog
andCat
have a method calledspeak()
. - When we call
animal.speak()
, Python knows which version to use based on the object. Dog
says Woof! andCat
says Meow!.
This is polymorphism — speak()
behaves differently for different objects.
Polymorphism in Daily Life
Here are some fun examples:
- You can draw with a pencil, pen, or crayon. Same action, different tools → different results.
- You can drive a car, a bike, or a truck. Same action, different vehicles → different behavior.
Why Learn Polymorphism?
- It makes your code more flexible and reusable.
- You can write one function or method and use it for many types of data.
Conclusion
Polymorphism allows the same action to work differently depending on the object.
Comments
Loading comments...