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

  1. Duck Typing / Method Polymorphism (Same method name, different classes)

  2. Operator Overloading (Same operator behaves differently)

  3. 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.


 

Output:

Some generic sound
Woof! Woof!

 5️⃣ Polymorphism With Built-in Functions


Same function (len) works on different data types.


 6️⃣ Summary Table

TypeExample
Duck Typing / Method Polymorphismspeak() in Dog & Cat
Operator Overloading+ behaves differently for int, str, objects
Method OverridingChild class method overrides parent method
Built-in Function Polymorphismlen() works on strings, lists, tuples

 7️⃣ Real-World Example: Payment System


 

Same function process_payment works for different payment methods — this is polymorphism.


Polymorphism makes code flexible, reusable, and clean.

You may also like...