Introduction π
**Polymorphism** is a core concept in Object-Oriented Programming (OOP). It means **one action β many forms**, allowing different classes to use the same method name but implement their own behavior.
Note
Makes code flexible, reusable, and extendable.
1. Simple Example of Polymorphism π§±
simple_polymorphism.py
class Dog:
def sound(self):
return "Bark"
class Cat:
def sound(self):
return "Meow"
for animal in [Dog(), Cat()]:
print(animal.sound())β Both classes have sound()
β Python chooses the correct method at runtime
2. Polymorphism with Functions π
function_polymorphism.py
class Circle:
def draw(self):
print("Drawing Circle")
class Square:
def draw(self):
print("Drawing Square")
def render(shape):
shape.draw() # polymorphic call
render(Circle())
render(Square())β The same function behaves differently for different objects.
3. Polymorphism with Inheritance π§¬
inheritance_polymorphism.py
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
animals = [Animal(), Dog(), Cat()]
for a in animals:
print(a.sound())β Child classes override parent class methods
β Python calls the correct version during runtime
4. Method Overriding (Runtime Polymorphism) βοΈ
method_overriding.py
class Parent:
def show(self):
print("Parent class")
class Child(Parent):
def show(self):
print("Child class")
c = Child()
c.show()β Child class method overrides parent method
β Known as *runtime polymorphism*
5. Polymorphism with Abstract Methods π
abstract_polymorphism.py
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): pass
class Circle(Shape):
def area(self):
return 3.14 * 5 * 5
class Square(Shape):
def area(self):
return 4 * 4
for s in [Circle(), Square()]:
print(s.area())β Abstract classes enforce polymorphism
β All child classes must implement the abstract method
6. Operator Overloading (Polymorphism in Python Magic Methods) β‘
Python allows polymorphism through special methods like __add__, __len__, etc.
operator_overloading.py
class Book:
def __init__(self, pages):
self.pages = pages
def __add__(self, other):
return self.pages + other.pages
b1 = Book(100)
b2 = Book(150)
print(b1 + b2) # 250β Polymorphism applied to operators
β + behaves differently depending on object type
7. Built-in Polymorphism in Python π
built_in_polymorphism.py
print(len("Hello")) # 5
print(len([1, 2, 3])) # 3β len() works for strings, lists, tuples, etc.
β Same function, different behavior β polymorphism!
8. Polymorphism in Real Projects π
- β UI frameworks: draw() for buttons, text fields, sliders
- β Game engines: attack() for different characters
- β APIs: process_request() for different request types
- β Billing systems: calculate_bill() for different customers
9. Best Practices π‘
- β Use method names consistently across related classes
- β Use abstraction to enforce polymorphism
- β Keep overridden methods simple and clear
- β Avoid unnecessary overriding
10. Final Example β Payment System π³
payment_polymorphism.py
class Payment:
def pay(self, amount):
print("Processing payment")
class CardPayment(Payment):
def pay(self, amount):
print(f"Paid {amount} using Card")
class UpiPayment(Payment):
def pay(self, amount):
print(f"Paid {amount} using UPI")
for method in [CardPayment(), UpiPayment()]:
method.pay(500)β A single method name pay() performs differently based on the object type.
Conclusion π
You now fully understand Polymorphism in Python! Want the next topic? Try Inheritance, Magic Methods, Method Resolution Order (MRO), or OOP Project Examples. Just tell me! π