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.
[Image visualizing the concept of Polymorphism: one interface, multiple forms (e.g., a "speak" command triggering a bark, a meow, and a chirp)]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.
Using len() with a List: Returns the number of elements in the list.
Using len() with a Dictionary: Returns the number of key–value pairs.
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:
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. Notice how the
Microwave
class inherits the generic
operate()
method, while the others define their own specific behavior.
