HOME HTML EDITOR C JAVA PHP python

Python Polymorphism

Polymorphism means "many forms." In Python, it allows different classes, functions, or operators to respond to the same interface or method name in ways suited to each object's type.

1. Class Polymorphism (Shared Method Names)

Different classes can define a method with the exact same name, allowing you to loop over distinct objects and call that method uniformly:

class CreditCard:
    def pay(self, amount):
        return f"Paid Rs.{amount} via Credit Card"

class UPIPayment:
    def pay(self, amount):
        return f"Paid Rs.{amount} via UPI"

class CashPayment:
    def pay(self, amount):
        return f"Paid Rs.{amount} in Cash"

methods = [CreditCard(), UPIPayment(), CashPayment()]
for m in methods:
    print(m.pay(500))

2. Polymorphism with Inheritance & Overriding

When subclasses override a method from a parent class, calling that method on each subclass instance executes its specialized version:

class Shape:
    def area(self):
        return 0

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

for shape in (Square(4), Circle(3)):
    print("Area:", shape.area())

3. Duck Typing in Python

Python uses duck typing — if an object implements the required method or behavior, it can be used regardless of its explicit class hierarchy:

class Dog:
    def speak(self):
        return "Woof!"

class Robot:
    def speak(self):
        return "Beep Boop!"

def announce(speaker):
    print(speaker.speak())

announce(Dog())
announce(Robot())
Tip: Even built-in functions like len() are polymorphic — they work on strings, lists, tuples, dictionaries, and sets alike.