Python Polymorphism
The term polymorphism comes from Greek words meaning “many forms.”
In programming, polymorphism allows the same function or method name to behave differently depending on the object or data type it is used with.
This makes code flexible, reusable, and easier to extend.
Function Polymorphism
In Python, many built-in functions work with different data types.
The behavior changes automatically based on the object passed.
Example: len() Function
Using len() with a String
Returns the total number of characters.
Output:
Using len() with a List
Returns the number of elements in the list.
Output:
Using len() with a Dictionary
Returns the number of key–value pairs.
Output:
Even though the function name is the same, it behaves differently for each data type. This is function polymorphism.
Polymorphism with Classes
Polymorphism is commonly used in object-oriented programming when multiple classes share the same method name but implement it in different ways.
Example
Different classes responding differently to the same method call:
Output:
Cat meows
Bird chirps
Each object responds to speak() in its own way, even though the method name
is identical.
Polymorphism Using Inheritance
Polymorphism also works with parent and child classes.
Child classes can inherit methods from a parent class and override them if needed.
Example
Create a base class and multiple child classes:
Output:
Washing clothes
Samsung Fridge
Cooling food
IFB Microwave
Appliance is operating
