π¦ Polymorphism in Python
πΉ DefinitionPolymorphism in Python means βone name, many forms.β In simple words, polymorphism allows the same function or method name to behave differently depending on the object that is calling it.
It helps programs become more flexible and easier to extend. Instead of writing separate code for each situation, polymorphism lets us use a single interface that works in different ways.
In real life, the same action can produce different results. For example, the word βrunβ has different meanings when used for a person, a machine, or a computer program. Python follows the same idea in programming.
π Basic Syntax Idea
Polymorphism usually appears through:
- Method overriding
- Function polymorphism
- Operator overloading
- Duck typing
There is no special keyword for polymorphism in Python.
π Examples of Polymorphism in Python
1οΈβ£ Polymorphism using Method Overriding
Example
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
a1 = Dog()
a2 = Cat()
a1.speak()
a2.speak()
Here, the method speak() has the same name but behaves differently for Dog and Cat. This is polymorphism through method overriding.
2οΈβ£ Polymorphism using a Function
Example
def add(a, b, c=0):
return a + b + c
print(add(2, 3))
print(add(2, 3, 4))
The same function add() works with different numbers of arguments. This shows function polymorphism.
3οΈβ£ Polymorphism using Different Classes (Duck Typing)
Example
class Car:
def move(self):
print("Car drives on road")
class Boat:
def move(self):
print("Boat moves in water")
for vehicle in (Car(), Boat()):
vehicle.move()
Different objects respond differently to the same method call. Python only checks whether the method exists, not the object type. This is known as duck typing.
π Key Points to Remember
- Same method name can behave differently
- Improves flexibility and reusability
- Achieved without special keywords
- Supports clean and extensible code
π Conclusion
Polymorphism makes Python programs flexible, reusable, and clean. It allows one interface to work with different data types or objects, reducing complexity and improving readability. It is a key pillar of object-oriented programming.