PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python Object-Oriented Programming (OOP) » Polymorphism in Python

Polymorphism in Python

Updated on: December 4, 2026 | 15 Comments

Object-Oriented Programming (OOP) has four essential characteristics: abstraction, encapsulation, inheritance, and polymorphism.

This lesson covers what polymorphism is and how to implement it in Python. You’ll learn how to implement polymorphism using method overriding, duck typing, abstract base classes, method overloading, and operator overloading.

Table of contents

  • What is Polymorphism in Python?
    • Polymorphism in Built-in function len()
  • Polymorphism With Inheritance
    • Example: Method Overriding
    • Override Built-in Functions
  • Polymorphism With Different Classes (Duck Typing)
    • Polymorphism with Function and Objects
  • Polymorphism With Abstract Base Classes
  • Polymorphism In Built-in Methods
  • Method Overloading
  • Operator Overloading in Python
    • Overloading + operator for custom objects
    • Overloading the * Operator
    • Overloading Comparison Operators
    • Magic Methods
  • Summary

What is Polymorphism in Python?

The word polymorphism comes from the Greek words poly (many) and morph (forms). In Python, polymorphism is the ability of an object or a function to take many forms. In simple words, polymorphism lets us perform the same action in many different ways.

For example, Jessa acts as an employee when she is at the office. At home, she acts as a wife and a mother. She represents herself differently in different places. So the same person takes different forms depending on the situation.

person takes different forms
A person takes different forms

With polymorphism, the same function or method name can process objects differently depending on their class or data type. Let’s see simple examples to understand it better.

Polymorphism in Built-in function len()

The built-in function len() calculates the length of an object depending on its type. If the object is a string, it returns the number of characters. If the object is a list, it returns the number of items in the list.

So the same len() function treats each object according to its type.

Example:

students = ['Emma', 'Jessa', 'Kelly']
school = 'ABC School'

# calculate count
print(len(students))
print(len(school))Code language: Python (python)

Output

3
10
Polymorphic len() function
Polymorphic len() function

Polymorphism With Inheritance

Polymorphism is most often used with inheritance. In inheritance, a child class inherits the attributes and methods of a parent class. The existing class is called a base class or parent class, and the new class is called a subclass, child class, or derived class.

Using method overriding, we can define methods in the child class with the same name as methods in the parent class. This process of re-implementing an inherited method in the child class is known as method overriding.

Advantages of method overriding

  • It’s useful when we want to extend or change the behavior of an inherited method, or when the parent’s method doesn’t fit the child class’s needs. We re-implement the same method in the child class in a different way.
  • When a parent class has several child classes, one child class can redefine a method while the others keep using the parent’s version. We don’t need to modify the parent class code.

When we call a method, Python checks the object’s class and runs the matching method. For example, if you create a Car object, Python calls the max_speed() method from the Car class.

Let’s see how it works with the help of an example.

Example: Method Overriding

In this example, Vehicle is the parent class and Car is its subclass. Each vehicle can have a different seating capacity, speed, and so on, so we can use the same instance method name in each class with a different implementation. This makes the code easy to extend and maintain over time.

Polymorphism with Inheritance
Polymorphism with Inheritance
class Vehicle:

    def __init__(self, name, color, price):
        self.name = name
        self.color = color
        self.price = price

    def show(self):
        print('Details:', self.name, self.color, self.price)

    def max_speed(self):
        print('Vehicle max speed is 150')

    def change_gear(self):
        print('Vehicle change 6 gear')


# inherit from vehicle class
class Car(Vehicle):
    def max_speed(self):
        print('Car max speed is 240')

    def change_gear(self):
        print('Car change 7 gear')


# Car Object
car = Car('Car x1', 'Red', 20000)
car.show()
# calls methods from Car class
car.max_speed()
car.change_gear()

# Vehicle Object
vehicle = Vehicle('Truck x1', 'white', 75000)
vehicle.show()
# calls method from a Vehicle class
vehicle.max_speed()
vehicle.change_gear()Code language: Python (python)

Output:

Details: Car x1 Red 20000
Car max speed is 240
Car change 7 gear
Details: Truck x1 white 75000
Vehicle max speed is 150
Vehicle change 6 gear

As you can see, because of polymorphism, Python recognizes that the max_speed() and change_gear() methods are overridden for the car object, so it uses the versions defined in the child class (Car).

On the other hand, the show() method isn’t overridden in the Car class, so the version from the Vehicle class is used.

Override Built-in Functions

In Python, we can control how built-in functions behave for our own objects. For example, we can make len(), abs(), or str() work with our class by defining the matching special method (__len__(), __abs__(), or __str__()) in the class. Let’s see an example.

Example

In this example, we redefine how len() works for a Shopping object by implementing __len__().

class Shopping:
    def __init__(self, basket, buyer):
        self.basket = list(basket)
        self.buyer = buyer

    def __len__(self):
        print('Redefine length')
        count = len(self.basket)
        # count total items in a different way
        # e.g. a pair of shoes, or a shirt + pants set
        return count * 2

shopping = Shopping(['Shoes', 'dress'], 'Jessa')
print(len(shopping))
Code language: Python (python)

Output

Redefine length
4

Polymorphism With Different Classes (Duck Typing)

In Python, polymorphism doesn’t require inheritance. Different classes can simply have methods with the same name. We can group objects of these classes in a list or tuple and call their methods without checking each object’s type. Python checks the type at runtime and calls the correct method.

This style is called duck typing: “If it walks like a duck and quacks like a duck, it’s a duck.” Python doesn’t care what class an object is, only whether it has the method you’re calling.

  • Design two or more classes that have the same method names.
  • Create an object of each class.
  • Add all the objects to a tuple.
  • Iterate the tuple using a for loop and call each object’s methods without checking its class.

Example

In the below example, fuel_type() and max_speed() are instance methods defined in both classes.

class Ferrari:
    def fuel_type(self):
        print("Petrol")

    def max_speed(self):
        print("Max speed 350")

class BMW:
    def fuel_type(self):
        print("Diesel")

    def max_speed(self):
        print("Max speed is 240")

ferrari = Ferrari()
bmw = BMW()

# iterate objects of different classes
for car in (ferrari, bmw):
    # call methods without checking class of object
    car.fuel_type()
    car.max_speed()Code language: Python (python)

Output

Petrol
Max speed 350
Diesel
Max speed is 240

As you can see, we created two classes, Ferrari and BMW, with the same instance method names fuel_type() and max_speed(). The two classes aren’t linked, and they don’t use inheritance.

We packed the two objects into a tuple and iterated through it using the car variable. This works because both classes have the same methods. For each object, Python looks up the method in that object’s own class and runs it.

Polymorphism with Function and Objects

We can also write a function that takes any object as a parameter and calls its methods without checking its class. This way, one function works for many types of objects, instead of repeating the same method calls.

Example

class Ferrari:
    def fuel_type(self):
        print("Petrol")

    def max_speed(self):
        print("Max speed 350")

class BMW:
    def fuel_type(self):
        print("Diesel")

    def max_speed(self):
        print("Max speed is 240")

# normal function
def car_details(obj):
    obj.fuel_type()
    obj.max_speed()

ferrari = Ferrari()
bmw = BMW()

car_details(ferrari)
car_details(bmw)
Code language: Python (python)

Output

Petrol
Max speed 350
Diesel
Max speed is 240

The function doesn’t even need the objects to be cars. Any object with the right method works:

class Duck:
    def speak(self):
        return 'Quack'

class Robot:
    def speak(self):
        return 'Beep boop'

def make_it_speak(thing):
    # works with any object that has a speak() method
    print(thing.speak())

make_it_speak(Duck())
make_it_speak(Robot())Code language: Python (python)

Output

Quack
Beep boop

Polymorphism With Abstract Base Classes

Duck typing is flexible, but nothing forces a class to actually implement the method you need. To enforce a common interface, use an abstract base class from the abc module. A method marked with @abstractmethod must be implemented by every subclass. You can’t create an object of the abstract class itself, or of a subclass that doesn’t implement the method.

from abc import ABC, abstractmethod

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

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 round(3.14159 * self.radius ** 2, 2)

# same method call, different behavior
for shape in (Square(4), Circle(3)):
    print(type(shape).__name__, 'area:', shape.area())

try:
    s = Shape()
except TypeError as e:
    print('Error:', e)Code language: Python (python)

Output

Square area: 16
Circle area: 28.27
Error: Can't instantiate abstract class Shape without an implementation for abstract method 'area'

Polymorphism In Built-in Methods

Many built-in functions are polymorphic: they process objects differently depending on the class or data type.

For example, the built-in function reversed(obj) returns an iterator over the given sequence in reverse order. If you pass a string, it reverses the characters. If you pass a list of strings, it reverses the order of the elements (it doesn’t reverse the individual strings).

Let’s see how a built-in function processes objects of different data types.

Example:

print('Reverse string')
for i in reversed('PYnative'):
    print(i, end=' ')

print('\nReverse list')
for i in reversed(['Emma', 'Jessa', 'Kelly']):
    print(i, end=' ')Code language: Python (python)

Output:

Reverse string
e v i t a n Y P
Reverse list
Kelly Jessa Emma

Method Overloading

Method overloading means defining several methods with the same name but different parameters. Python doesn’t support method overloading in this way. If you define the same function or method name twice, Python keeps only the last definition, and calling it with a different number of arguments raises a TypeError.

Example

def addition(a, b):
    c = a + b
    print(c)


def addition(a, b, c):
    d = a + b + c
    print(d)


# the below line shows an error
# addition(4, 5)

# This line will call the second addition() function
addition(3, 7, 5)
Code language: Python (python)

Output:

15

To get the same effect, write a single method whose behavior depends on the arguments passed, using default arguments or *args.

For example, the built-in function range() takes up to three arguments and produces different results depending on how many are passed.

Example:

for i in range(5): print(i, end=', ')
print()
for i in range(5, 10): print(i, end=', ')
print()
for i in range(2, 12, 2): print(i, end=', ')Code language: Python (python)

Output:

0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
2, 4, 6, 8, 10,

Let’s write an area() method that calculates the area of a square or a rectangle, depending on the number of arguments passed to it.

  • If one argument is passed, it calculates the area of a square.
  • If two arguments are passed, it calculates the area of a rectangle.

Example: User-defined polymorphic method

class Shape:
    # method with one default parameter
    def area(self, a, b=0):
        if b > 0:
            print('Area of Rectangle is:', a * b)
        else:
            print('Area of Square is:', a ** 2)

square = Shape()
square.area(5)

rectangle = Shape()
rectangle.area(5, 3)
Code language: Python (python)

Output:

Area of Square is: 25
Area of Rectangle is: 15

Operator Overloading in Python

Operator overloading means changing the behavior of an operator depending on the operands (values) it’s used with. In other words, the same operator can be used for multiple purposes.

For example, the + operator performs arithmetic addition when used with numbers, and concatenation when used with strings or lists.

Using the same + operator for different data types is one of the simplest examples of polymorphism in Python.

Example:

# add 2 numbers
print(100 + 200)

# concatenate two strings
print('Jess' + 'Roy')

# merge two lists
print([10, 20, 30] + ['jessa', 'emma', 'kelly'])
Code language: Python (python)

Output:

300
JessRoy
[10, 20, 30, 'jessa', 'emma', 'kelly']

Overloading + operator for custom objects

Suppose we have two objects and we want to add them with the + operator. By default, this raises an error, because Python doesn’t know how to add two objects of our class. See the following example.

Example:

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

# creating two objects
b1 = Book(400)
b2 = Book(300)

# add two objects
print(b1 + b2)
Code language: Python (python)

Output

TypeError: unsupported operand type(s) for +: 'Book' and 'Book'

We can overload the + operator so it works with our objects. Python provides special methods, also called magic or dunder methods, that are called automatically when an operator is used.

For example, when we use the + operator, Python automatically calls the magic method __add__(). To add two custom objects, we define this method in our class.

Example:

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

    # Overloading + operator with magic method
    def __add__(self, other):
        return self.pages + other.pages

b1 = Book(400)
b2 = Book(300)
print("Total number of pages:", b1 + b2)
Code language: Python (python)

Output

Total number of pages: 700

Overloading the * Operator

The * operator performs multiplication. Internally, the * operator calls the __mul__() method. Let’s overload it to calculate an employee’s salary for a specific period.

Example:

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def __mul__(self, timesheet):
        print('Worked for', timesheet.days, 'days')
        # calculate salary
        return self.salary * timesheet.days


class TimeSheet:
    def __init__(self, name, days):
        self.name = name
        self.days = days


emp = Employee("Jessa", 800)
timesheet = TimeSheet("Jessa", 50)
print("Salary is:", emp * timesheet)
Code language: Python (python)

Output

Worked for 50 days
Salary is: 40000

Overloading Comparison Operators

We can also overload comparison operators such as == and <. In the following example, __add__() returns a new Money object instead of a plain number, __str__() controls how the object is printed, and __lt__() lets built-in functions like min() compare Money objects.

class Money:
    def __init__(self, amount):
        self.amount = amount

    def __add__(self, other):
        # return a new Money object
        return Money(self.amount + other.amount)

    def __eq__(self, other):
        return self.amount == other.amount

    def __lt__(self, other):
        return self.amount < other.amount

    def __str__(self):
        return f'${self.amount}'

a = Money(50)
b = Money(30)
print(a + b)
print(a == Money(50))
print(b < a)
print(min(a, b, Money(10)))Code language: Python (python)

Output

$80
True
True
$10

Magic Methods

Python has a magic method for each operator you can overload. The table below lists the magic methods for the arithmetic, augmented assignment, and comparison operators in Python 3.

Operator NameSymbolMagic method
Addition+__add__(self, other)
Subtraction-__sub__(self, other)
Multiplication*__mul__(self, other)
Division/__truediv__(self, other)
Floor Division//__floordiv__(self, other)
Modulus%__mod__(self, other)
Power**__pow__(self, other)
Add and assign+=__iadd__(self, other)
Subtract and assign-=__isub__(self, other)
Multiply and assign*=__imul__(self, other)
Divide and assign/=__itruediv__(self, other)
Modulus and assign%=__imod__(self, other)
Power and assign**=__ipow__(self, other)
Less than<__lt__(self, other)
Greater than>__gt__(self, other)
Less than or equal to<=__le__(self, other)
Greater than or equal to>=__ge__(self, other)
Equal to==__eq__(self, other)
Not equal!=__ne__(self, other)
magic methods

Note: If you don’t define an augmented method like __iadd__(), Python falls back to the regular method (__add__()) for +=. Similarly, if __ne__() isn’t defined, Python uses the opposite of __eq__().

Summary

  • Polymorphism means the same function, method, or operator works differently depending on the object it’s used with.
  • With inheritance, a child class can override a parent method, and Python calls the version that matches the object’s class.
  • With duck typing, unrelated classes just need methods with the same name. Python doesn’t check the type.
  • Abstract base classes (abc.ABC with @abstractmethod) enforce that subclasses implement the required methods.
  • Python doesn’t support classic method overloading. Use default arguments or *args instead.
  • Operator overloading uses magic methods such as __add__(), __mul__(), __eq__(), and __lt__().

Filed Under: Python, Python Object-Oriented Programming (OOP)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Object-Oriented Programming (OOP)

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Object-Oriented Programming (OOP)
TweetF  sharein  shareP  Pin

  Python OOP

  • Python OOP
  • Classes and Objects in Python
  • Constructors in Python
  • Python Destructors
  • Encapsulation in Python
  • Polymorphism in Python
  • Inheritance in Python
  • Python Instance Variables
  • Python Instance Methods
  • Python Class Variables
  • Python Class Method
  • Python Static Method
  • Python Class Method vs. Static Method vs. Instance Method
  • Python OOP exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com