Polymorphism in Python
1. What is Polymorphism
Polymorphism allows the same interface (method or operator) to behave differently based on the object or context.
print(len("Python")) # String length
print(len([1, 2, 3])) # List lengthThe same function works for multiple data types.
2. Function Polymorphism
def add(a, b, c=0):
return a + b + c
print(add(2, 3)) # 5
print(add(2, 3, 4)) # 9A single function adapts behavior based on arguments.
3. Built-in Polymorphism
print(5 + 10) # Integer addition
print("Hello " + "AI") # String concatenationThe + operator behaves differently based on operand types.
4. Method Overriding (Runtime Polymorphism)
Child class alters the behavior of a parent method.
5. Operator Overloading
Custom behavior for operators using magic methods.
6. Polymorphism with Different Classes
Different objects responding to the same method call.
7. Duck Typing
Behavior is determined by method presence, not class type.
8. Method Overloading via Default Arguments
Python simulates overloading using default parameters.
9. Abstract Base Class Polymorphism
Ensures consistent interface across implementations.
10. Real-World Polymorphism Example
Multiple behaviors implemented under a unified interface.
Recommended Next Topics
To continue the structured Python OOP series, the next logical sections are:
Python Encapsulation
Last updated