Ad – 728Γ—90
πŸ—οΈ OOP

Python Polymorphism – One Interface, Many Implementations

Polymorphism means "many forms". In Python, polymorphism lets different classes respond to the same method call in their own way. You can call area() on a Circle, a Rectangle, or a Triangle β€” each calculates it differently but the interface is identical. This is the power of polymorphism.

⏱️ 20 min read🎯 IntermediateπŸ“… Updated 2026

Method Overriding

A subclass can override a parent method to change its behaviour.

Python
class Animal:
    def speak(self):
        return "..."

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

class Cat(Animal):
    def speak(self):        # Override
        return "Meow!"

class Duck(Animal):
    def speak(self):
        return "Quack!"

animals = [Dog(), Cat(), Duck()]
for animal in animals:
    print(animal.speak())   # Each responds differently
β–Ά Output
Woof! Meow! Quack!

Duck Typing

"If it walks like a duck and quacks like a duck, it's a duck." Python doesn't require inheritance β€” any object with the right method works.

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

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

class Human:
    def speak(self): return "Hello!"

# No shared base class needed!
entities = [Dog(), Robot(), Human()]
for e in entities:
    print(e.speak())
β–Ά Output
Woof! Beep boop! Hello!

Polymorphism with Abstract Methods

Use ABC to enforce that subclasses implement required methods.

Python
from abc import ABC, abstractmethod
import math

class Shape(ABC):
    @abstractmethod
    def area(self): ...

    @abstractmethod
    def perimeter(self): ...

class Circle(Shape):
    def __init__(self, r): self.r = r
    def area(self): return math.pi * self.r**2
    def perimeter(self): return 2 * math.pi * self.r

class Square(Shape):
    def __init__(self, s): self.s = s
    def area(self): return self.s**2
    def perimeter(self): return 4 * self.s

for shape in [Circle(5), Square(4)]:
    print(f"Area: {shape.area():.2f}, Perimeter: {shape.perimeter():.2f}")
β–Ά Output
Area: 78.54, Perimeter: 31.42 Area: 16.00, Perimeter: 16.00
Ad – 336Γ—280

Operator Overloading

Define special methods to make operators work with your classes.

Python
class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)

    def __str__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(1, 2)
v2 = Vector(3, 4)

print(v1 + v2)    # Vector(4, 6)
print(v1 * 3)     # Vector(3, 6)
β–Ά Output
Vector(4, 6) Vector(3, 6)