πŸŒ€ Python OOP β€” Polymorphism

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

πŸ’‘ Polymorphism = β€œSame method name, different implementations.”
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 πŸŽ‰

>>β€œPolymorphism brings flexibility to OOP β€” one interface, multiple behaviors.” ✨

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! 😊