Python Docs

Python Polymorphism — Complete Cheat Sheet

What is Polymorphism?

Polymorphism means "many forms". In OOP, it allows different classes to have methods with the same name that behave differently.

Example: Different objects can have a method named sound(), but each object implements it in its own way.

Basic Polymorphism Example

class Bird:
  def sound(self):
    print("Chirp")

class Dog:
  def sound(self):
    print("Bark")

for animal in (Bird(), Dog()):
  animal.sound()

Polymorphism Through Method Overriding

Child classes override parent methods to give their own behaviour.

class Animal:
  def speak(self):
    print("Animal speaks")

class Cat(Animal):
  def speak(self):
    print("Meow")

class Dog(Animal):
  def speak(self):
    print("Bark")

for pet in (Cat(), Dog()):
  pet.speak()

Polymorphism with Functions

A single function can take different types of objects and call the same-named method on them.

def greet(obj):
  obj.say_hello()

class English:
  def say_hello(self):
    print("Hello")

class Spanish:
  def say_hello(self):
    print("Hola")

greet(English())
greet(Spanish())

Duck Typing in Python

Python follows "If it walks like a duck and quacks like a duck, it is a duck". If an object has the required method, Python calls it, regardless of the class.

class Car:
  def start(self):
    print("Car engine started")

class Laptop:
  def start(self):
    print("Laptop turning on")

def begin(device):
  device.start()

begin(Car())
begin(Laptop())

Polymorphism in Inheritance

class Shape:
  def area(self):
    return "Undefined"

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

class Circle(Shape):
  def __init__(self, r):
    self.r = r
  def area(self):
    return 3.14 * self.r * self.r

for s in (Square(4), Circle(3)):
  print(s.area())

Types of Polymorphism in Python

TypeDescription
Compile-Time (Not in Python)Python does not support traditional function overloading by signature.
Run-Time PolymorphismAchieved mainly using method overriding in inheritance.
Duck TypingIf an object has the expected method, Python runs it.
Operator PolymorphismSame operator behaves differently (for example, + adds numbers, concatenates strings, or extends lists).

Summary

  • Polymorphism allows the same method name to behave differently on different objects.
  • Method overriding in inheritance is the most common pattern.
  • Functions can work with any object that provides the expected method.
  • Python relies on duck typing: behavior matters more than type.
  • Polymorphism improves flexibility and reduces code repetition.