Polymorphism is one of the core concepts of Object-Oriented Programming (OOP). The word polymorphism means “many forms”.
In Python, polymorphism allows the same function or method name to behave differently depending on the object or data it is used with.
Polymorphism is:
The ability of a function, method, or operator to perform different tasks based on the context.
print(len("Hello")) # String length
print(len([1, 2, 3])) # List length
Output
5
3
Explanation
len() works differently for different data types.print(2 + 3) # Addition
print("Hello " + "World") # String concatenation
Output
5
Hello World
Explanation
+ operator behaves differently based on operand types.When a child class provides its own implementation of a method that is already defined in the parent class.
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
class Cat(Animal):
def sound(self):
print("Cat meows")
a = Animal()
d = Dog()
c = Cat()
a.sound()
d.sound()
c.sound()
Output
Animal makes sound
Dog barks
Cat meows
Python does not support traditional method overloading, but it can be achieved using default arguments.
def add(a, b=0, c=0):
return a + b + c
print(add(2, 3))
print(add(2, 3, 4))
Python follows duck typing, which is a form of polymorphism.
“If it looks like a duck and behaves like a duck, it is treated as a duck.”
class Dog:
def speak(self):
print("Bark")
class Cat:
def speak(self):
print("Meow")
def make_sound(animal):
animal.speak()
make_sound(Dog())
make_sound(Cat())
Polymorphism means one name, many forms.
It allows the same function or method to behave differently.
Types include:
Python uses duck typing to support polymorphism.
It is essential for writing flexible and reusable code.