Python Polymorphism


Polymorphism is an important concept in Object Oriented Programming. It allows different classes to use the same method name but behave in their own way. The word polymorphism means “many forms,” and that is exactly what it does. It lets you write cleaner and more flexible code because the same action can work differently depending on the object.

In this tutorial, you will learn how polymorphism works in Python, how method overriding supports polymorphism, how built-in functions use it, and how to apply it in practical real-world programs.

What Is Polymorphism?

Polymorphism means a single method name can work with different types of objects. The method calls may look the same, but the result depends on which object is calling it.

Example:

class Dog:
    def sound(self):
        print("Dog barks.")

class Cat:
    def sound(self):
        print("Cat meows.")

Both classes have a method named sound(), but the behaviour is different.

Why Polymorphism Is Useful

Polymorphism helps your program remain simple even when it works with many types of objects. Instead of writing separate code for each class, you write one structure that works for all, and each object decides how it behaves.

You can:

  • Use the same method name in multiple classes

  • Handle different objects in a unified way

  • Reduce repeated code

  • Make your program more flexible and scalable

This feature is used in most real Python projects.

Polymorphism With Class Methods

The most common way to use polymorphism is through methods in different classes.

Example:

class Bird:
    def sound(self):
        print("Bird chirps.")

class Duck:
    def sound(self):
        print("Duck quacks.")

Now you can do:

for obj in (Bird(), Duck()):
    obj.sound()

Each object will run its own version of the method.

Polymorphism With Inheritance

Polymorphism often works together with inheritance. When a child class overrides a method from the parent class, Python automatically uses the child’s version.

Example:

class Shape:
    def area(self):
        print("Area method not defined.")

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

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

Calling:

s = Square(5)
s.area()

The child class version is used.

Using Built-in Functions With Polymorphism

Python’s built-in functions are designed to handle different object types, which is also a form of polymorphism.

len() Example

print(len("Python"))
print(len([1, 2, 3, 4]))
print(len({"a": 1, "b": 2}))

The len() function works with strings, lists, and dictionaries, even though they are completely different types.

+ Operator Example

print(2 + 3)
print("Hello " + "World")

The + operator adds numbers, but it joins strings. This is operator polymorphism.

Function Polymorphism With Different Objects

You can write a single function that works with different types of objects as long as they contain the required method.

Example:

class Car:
    def move(self):
        print("Car is moving.")

class Bike:
    def move(self):
        print("Bike is running.")

Function:

def start(vehicle):
    vehicle.move()

Usage:

start(Car())
start(Bike())

The same function works for both objects.

Real Life Example: Payment System

Let’s say you are building a payment system. You can use polymorphism to process different payment methods.

class CreditCard:
    def pay(self, amount):
        print("Paid", amount, "using Credit Card.")

class UPI:
    def pay(self, amount):
        print("Paid", amount, "using UPI.")

class NetBanking:
    def pay(self, amount):
        print("Paid", amount, "using Net Banking.")

Now one function handles all:

def process(payment, amount):
    payment.pay(amount)

Usage:

process(UPI(), 500)
process(CreditCard(), 750)
process(NetBanking(), 1200)

Each payment type runs its own version of the pay() method.

Method Overriding

When a child class changes a parent method, it supports polymorphism automatically.

Example:

class Animal:
    def sound(self):
        print("Animal makes a sound.")

class Lion(Animal):
    def sound(self):
        print("Lion roars.")

Calling:

l = Lion()
l.sound()

Runs the overridden method.

Polymorphism With Abstract Classes

Abstract classes allow you to force child classes to implement specific methods. This ensures consistent behaviour while still allowing different implementations.

Example:

from abc import ABC, abstractmethod

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

Child classes:

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

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

Polymorphism:

shapes = [Circle(5)]
for s in shapes:
    print(s.area())

Each class gives its own result.

Operator Overloading

Python lets you define how operators work with your own classes. This is another form of polymorphism.

Example:

class Book:
    def __init__(self, pages):
        self.pages = pages

    def __add__(self, other):
        return self.pages + other.pages

Usage:

b1 = Book(150)
b2 = Book(200)
print(b1 + b2)

The + operator now adds pages of two Book objects.

Practical Examples

  1. Sound System

for a in (Dog(), Cat()):
    a.sound()
  1. Shape Area

print(Circle(3).area())
  1. Multiple Vehicle Types

start(Car())
  1. Using Operator Overloading

print(b1 + b2)
  1. Working With Lists of Objects

for p in [UPI(), CreditCard(), NetBanking()]:
    p.pay(500)
  1. Overriding Parent Methods

Lion().sound()
  1. Using Abstract Methods

print(Circle(4).area())
  1. Uniform Function

def action(obj):
    obj.work()
  1. Polymorphism in Games

player.attack()
enemy.attack()
  1. File Handling Objects

Different readers can implement their own read() method.

Summary of the Tutorial

Polymorphism lets you use the same method name across different classes. Each class can define its own version of the method, making your code flexible and easier to manage. It supports method overriding, works with built-in functions like len(), powers operator overloading, and helps you write programs that handle multiple object types without extra conditions. It is a fundamental part of Python OOP and is used everywhere from small scripts to large applications.


Practice Questions

Q1. Write a Python program to create two different classes with a method named describe() that prints different outputs.

Q2. Write a Python program to use a for loop to call the same describe() method from different class instances.

Q3. Write a Python program to override a method from a parent class in two different child classes and demonstrate the outputs.

Q4. Write a Python program to create a base class Vehicle with a start() method, then override it in Car and Bike classes.

Q5. Write a Python program to use a single function to call start() on different objects like Car and Bike, demonstrating polymorphism.

Q6. Write a Python program to create a class Bird with a method fly(), then override it in Eagle and Penguin classes with different behavior.

Q7. Write a Python program to store different animal objects in a list and call a common method like make_sound() for each.

Q8. Write a Python program to create a base class with a greet() method and override it in Student and Teacher classes.

Q9. Write a Python program to demonstrate polymorphism using a function that takes any object with a run() method.

Q10. Write a Python program to build a simple game setup with a base class Character and different character types like Warrior, Mage, etc., each using polymorphic methods such as attack().


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top