Python Polymorphism
🐍 Python Polymorphism
Polymorphism is an OOP concept that means “many forms”.
In Python, it allows objects of different classes to be treated in a similar way.
🔹 1️⃣ Types of Polymorphism in Python
-
Duck Typing / Method Polymorphism (Same method name, different classes)
-
Operator Overloading (Same operator behaves differently)
-
Method Overriding (Child class method overrides parent method)
🔹 2️⃣ Duck Typing Example (Method Polymorphism)
Python is dynamically typed, so it doesn’t care about the object type.
🔹 3️⃣ Operator Overloading
Operators like +, -, * can behave differently depending on data types.
__add__method allows overloading the + operator.
🔹 4️⃣ Method Overriding (Run-time Polymorphism)
Child class can override parent class method.
Can still call parent method using
super():
Output:
🔹 5️⃣ Polymorphism With Built-in Functions
Same function (
len) works on different data types.
🔹 6️⃣ Summary Table
| Type | Example |
|---|---|
| Duck Typing / Method Polymorphism | speak() in Dog & Cat |
| Operator Overloading | + behaves differently for int, str, objects |
| Method Overriding | Child class method overrides parent method |
| Built-in Function Polymorphism | len() works on strings, lists, tuples |
🔹 7️⃣ Real-World Example: Payment System
Same function
process_paymentworks for different payment methods — this is polymorphism.
Polymorphism makes code flexible, reusable, and clean.
