Lesson 53 of 70 – Python Polymorphism
76%

Python Polymorphism

Polymorphism is an important concept of Object Oriented Programming (OOP). The word polymorphism means "many forms". In Python, the same interface, method name, or operation can work differently depending on the object or data involved.

Note: Polymorphism allows different objects to respond to the same method call in their own way.

What is Polymorphism?

Polymorphism allows a common operation or method name to have different behavior for different objects.

class Dog:

    def sound(self):

        print("Bark")


class Cat:

    def sound(self):

        print("Meow")


dog = Dog()
cat = Cat()

dog.sound()
cat.sound()

Output:

Bark
Meow

Same Method Name in Different Classes

Different classes can define a method with the same name. The behavior can be different in each class.

class Dog:

    def speak(self):

        print("Dog barks")


class Cat:

    def speak(self):

        print("Cat meows")


dog = Dog()
cat = Cat()

dog.speak()
cat.speak()

Output:

Dog barks
Cat meows

Polymorphism with a Loop

A common method name can be called on different objects inside a loop. Each object provides its own implementation.

class Dog:

    def sound(self):

        print("Bark")


class Cat:

    def sound(self):

        print("Meow")


animals = [Dog(), Cat()]

for animal in animals:

    animal.sound()

Output:

Bark
Meow

Polymorphism with Inheritance

Polymorphism is often used with inheritance. A child class can override a method inherited from a parent class.

class Animal:

    def sound(self):

        print("Animal sound")


class Dog(Animal):

    def sound(self):

        print("Bark")


class Cat(Animal):

    def sound(self):

        print("Meow")


animals = [Dog(), Cat()]

for animal in animals:

    animal.sound()

Output:

Bark
Meow

Method Overriding

Method overriding occurs when a child class provides its own implementation of a method defined in its parent class.

class Vehicle:

    def move(self):

        print("Vehicle is moving")


class Car(Vehicle):

    def move(self):

        print("Car is driving")


car = Car()

car.move()

Output:

Car is driving

Duck Typing

Python often follows the principle known as duck typing. The important thing is whether an object supports the required operation, rather than whether it belongs to a particular class.

class Dog:

    def sound(self):

        print("Bark")


class Cat:

    def sound(self):

        print("Meow")


def make_sound(animal):

    animal.sound()


make_sound(Dog())

make_sound(Cat())

Output:

Bark
Meow

Polymorphism with Functions

A function can work with different objects as long as those objects provide the operation required by the function.

class Student:

    def show(self):

        print("Student")


class Teacher:

    def show(self):

        print("Teacher")


def display(obj):

    obj.show()


display(Student())

display(Teacher())

Output:

Student
Teacher

Polymorphism with Built-in Functions

Python's built-in functions can often work with different types of objects. For example, len() works with strings, lists, tuples, and many other objects that provide the required interface.

print(len("Python"))

print(len([10, 20, 30]))

print(len((1, 2, 3, 4)))

Output:

6
3
4

Operator Polymorphism

The same operator can perform different operations depending on the data type.

print(10 + 20)

print("Hello " + "Python")

print([1, 2] + [3, 4])

Output:

30
Hello Python
[1, 2, 3, 4]

The + operator performs numeric addition for numbers and concatenation for strings and lists.

One Function, Multiple Objects

class Circle:

    def area(self):

        print("Circle area")


class Square:

    def area(self):

        print("Square area")


def calculate_area(shape):

    shape.area()


calculate_area(Circle())

calculate_area(Square())

Output:

Circle area
Square area

Polymorphism with Abstract Classes

Abstract base classes can define a common interface that subclasses must implement.

from abc import ABC, abstractmethod


class Animal(ABC):

    @abstractmethod
    def sound(self):

        pass


class Dog(Animal):

    def sound(self):

        print("Bark")


class Cat(Animal):

    def sound(self):

        print("Meow")


animals = [Dog(), Cat()]

for animal in animals:

    animal.sound()

Output:

Bark
Meow

Common Interface

Polymorphism is useful when different classes provide the same interface. Code using the interface does not need to know the specific concrete class.

class PDF:

    def print_document(self):

        print("Printing PDF")


class Word:

    def print_document(self):

        print("Printing Word document")


documents = [
    PDF(),
    Word()
]

for document in documents:

    document.print_document()

Output:

Printing PDF
Printing Word document

Polymorphism with Object Data

class Student:

    def __init__(self, name):

        self.name = name


    def display(self):

        print("Student:", self.name)


class Teacher:

    def __init__(self, name):

        self.name = name


    def display(self):

        print("Teacher:", self.name)


people = [
    Student("Rahul"),
    Teacher("Amit")
]

for person in people:

    person.display()

Output:

Student: Rahul
Teacher: Amit

Practical Example – Payment System

Different payment classes can provide the same pay() method while implementing different payment behavior.

class CashPayment:

    def pay(self, amount):

        print("Paid by cash:", amount)


class CardPayment:

    def pay(self, amount):

        print("Paid by card:", amount)


class UPIPayment:

    def pay(self, amount):

        print("Paid by UPI:", amount)


payments = [
    CashPayment(),
    CardPayment(),
    UPIPayment()
]

for payment in payments:

    payment.pay(1000)

Output:

Paid by cash: 1000
Paid by card: 1000
Paid by UPI: 1000

Polymorphism and Inheritance

Polymorphism and inheritance are related but they are not the same concept.

Inheritance Polymorphism
Allows a class to reuse another class's behavior. Allows different objects to respond to the same interface.
Creates relationships between classes. Provides flexible behavior.
Uses parent and child classes. Can work with inheritance or duck typing.

Advantages of Polymorphism

  • Makes code more flexible.
  • Reduces the need for type-specific code.
  • Supports reusable functions.
  • Makes programs easier to extend.
  • Allows different objects to share a common interface.
  • Works naturally with inheritance and duck typing.

Real-World Example

Consider different types of vehicles. Each vehicle can have a move() method, but the way it moves can be different.

class Car:

    def move(self):

        print("Car drives")


class Boat:

    def move(self):

        print("Boat sails")


class Plane:

    def move(self):

        print("Plane flies")


vehicles = [
    Car(),
    Boat(),
    Plane()
]

for vehicle in vehicles:

    vehicle.move()

Output:

Car drives
Boat sails
Plane flies

Complete Polymorphism Example

class Employee:

    def work(self):

        print("Employee is working")


class Developer(Employee):

    def work(self):

        print("Developer writes code")


class Teacher(Employee):

    def work(self):

        print("Teacher teaches students")


class Manager(Employee):

    def work(self):

        print("Manager manages the team")


employees = [
    Developer(),
    Teacher(),
    Manager()
]

for employee in employees:

    employee.work()

Output:

Developer writes code
Teacher teaches students
Manager manages the team

Key Points

  • Polymorphism means "many forms".
  • The same method or interface can produce different behavior for different objects.
  • Method overriding is a common way to implement polymorphism with inheritance.
  • Python supports polymorphism through duck typing.
  • Different classes can implement the same method name.
  • A function can work with different objects when they provide the required interface.
  • Built-in functions such as len() demonstrate polymorphic behavior.
  • Operators such as + can behave differently depending on the operands.
  • Abstract base classes can define common interfaces for subclasses.
  • Polymorphism makes code flexible and easier to extend.

🧠 Quick Quiz

Question: What does polymorphism allow in Python?