Polymorphism is one of the core principles of Object-Oriented Programming (OOP).
The word Polymorphism means âmany forms.â
In programming, polymorphism allows the same method or function name to behave differently depending on the object that is using it.
In simple words:
One name â Multiple behaviors
Why Polymorphism is Important
- Increases flexibility
- Improves code reusability
- Makes code cleaner and more scalable
- Allows different objects to respond in their own way
1. Polymorphism with Functions
Different data types can use the same function.
print(len("Hira"))
print(len([1, 2, 3, 4]))
Output:
4
4
The len() function works with strings and lists, but behaves according to the data type.
2. Polymorphism with Method Overriding (Inheritance)
A child class can change the behavior of a parent class method.
class Animal:
def sound(self):
print("Some sound")class Dog(Animal):
def sound(self):
print("Bark")class Cat(Animal):
def sound(self):
print("Meow")d = Dog()
c = Cat()d.sound()
c.sound()
Output:
Bark
Meow
Here:
- Same method name
sound() - Different behavior depending on the object
3. Polymorphism Using Same Method Name in Different Classes
Even without inheritance, different classes can have the same method name.
class Bird:
def move(self):
print("Flying")class Fish:
def move(self):
print("Swimming")b = Bird()
f = Fish()b.move()
f.move()
Output:
Flying
Swimming
This is called Duck Typing in Python.
If it behaves like a duck, Python treats it like a duck.
Types of Polymorphism in Python
- Compile-time Polymorphism
Achieved through method overloading
(Python does not support traditional overloading, but default arguments can simulate it) - Runtime Polymorphism
Achieved through method overriding
Example of Simulated Method Overloading
class Math:
def add(self, a, b=0):
return a + bm = Math()
print(m.add(5))
print(m.add(5, 3))
Key Takeaway
Polymorphism allows one interface to be used for different data types or objects.
It helps make programs flexible, reusable, and easy to extend in Object-Oriented Programming.