View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

What is Polymorphism in Python? Polymorphism Explained with Examples

By Rohit Sharma

Updated on Oct 04, 2022 | 5 min read | 8.2k views

Share:

Introduction

Python is a high-level, interpreted, and open-sourced programming language. It has gained a lot of focus among many programmers and developers because it supported libraries that help in many tasks such as exploratory data analysis, GUI programming, etc. Also, programming in python is very interesting.

We are going to discuss an interesting feature of python in this article. So let’s get started!

Learn data science courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

What is Polymorphism?

The word polymorphism is derived from the Greek word poly (meaning many), and morphism (forms). It means a single function name or method name can have multiple forms. And this fulfils the wish of avoiding code duplication in the implementation.

But polymorphism in python is a little different from polymorphism in other programming languages. Programming languages like java and c++ support compile-time polymorphism (method overloading). In method overloading, multiple methods can have the same method name but differ in their parameter signature. This feature is not supported by python. If multiple methods have the same function, then the newest function implementation will override the earlier function implementation.

Function Polymorphism

Function polymorphism in python can be categorized into two user-defined polymorphism and pre-defined polymorphism.

We can implement user-defined polymorphism to call the same function with a different parameter signature, and this can be considered as a little compensation to the unavailability of method overloading in python. Let’s walk through an example code

def mul(a,b,c=1):
    return a*b*c;

print(mul(1,2,3))
print(mul(1,2))

In the above code, even though the number of parameters passed is not equal both the print statements refer to the same method. In the second function call, parameter c is assigned with a default value of 1.

Similarly few predefined methods in python exhibit polymorphism features, where a single method can accept parameters of different datatypes. Methods like len() exhibits this feature. And here’s the code to illustrate that.

print(len([1,2,3,4]))
print(len((1,2,3,4)))
print(len(“python”))
print(len({“key1”:“value1”,“key2”:“value2”}))

In the above code, the same len() method is used for a list, tuple, string, and dictionary.

Checkout: Python Applications in Real World

Operator Overloading

An operator like ‘+’ can be used in multiple ways. For example, it can be used to add two numbers, strings, as well as lists, etc. And here’s the code to demonstrate that.

l1=[1,2,3]
l2=[3,4,5]

n1=2
n2=3

s1=“hey”
s2=“there”

print(l+l1)
print(s1+s2)
print(n1+n2)

Method Overriding

Method overriding is also considered as runtime polymorphism, and it is supported by many languages like java, c++, and python.

This feature is related to inheritance, a child class in python inherits member functions and member variables from its parent class. And if we feel that the implementation of the parent class method is not relevant, then we can override that method in the child class. And modifying the member functions as per the requirement in the child class is referred to as method overriding.

class two_wheeler:
    def fuel(self):
        print(“two wheeler needs fuel to run”)
    def capacity(self):
        print(“bikes are suitable for a maximum of 2 people”)

class electric_bike(two_wheeler):
    def fuel(self):
        print(“electric bikes run on a battery”)
class petrol_bike(two_wheeler):
    def fuel(self):
        print(“petrol bike runs on petrol”)       
bike=two_wheeler()
ebike=electric_bike()
pbike=petrol_bike()

bike.fuel()
bike.capacity()
ebike.fuel()
ebike.capacity()
pbike.fuel()
pbike.capacity()

In the above code, two_wheeler is the parent class and electric_bike, petrol_bike are the child classes. And the methods fuel(), capacity() are inherited by the child classes electric_bike and petrol_bike. Now, we can update the implementation of the methods if required, and inside the electric_bike class we’ve reimplemented the fuel() method, similarly reimplemented the fuel() method in the petrol_bike class.

For example in the code ebike.fuel() prints “electric bikes run on a battery” and pbike.fuel() prints petrol bike runs on petrol”.

Read: Python Project Ideas & Topics

Polymorphism in Class Methods

Python allows different classes to have the same method name, and this comes under the polymorphism feature. And the invocation of the method is based on the object we use to call the method.

class bicycle:
    def fuel(self):
        print(“bicycle doesn’t need any fuel!”)
    def capacity(self):
        print(“bicycles are suitable for single person ride”)

class electric_bike:
    def fuel(self):
        print(“electric bikes run on battery”)
    def capacity(self):
        print(“electric bikes are suitable for maximum  of 2 people”)

class petrol_bike:
    def fuel(self):
        print(“petrol bike runs on petrol”)
    def capacity(self):
        print(“petrol bikes are suitable for maximum of 2 people”)
       
ecobike=bicycle()
ebike=electric_bike()
pbike=petrol_bike()
l=[ecobike,ebike,pbike]

for obj in l:
    obj.fuel()
    obj.capacity()

In the above code, we’ve created three objects of the three classes bicycle, electric_bike, and petrol_bike. And all three classes have the same method names. Now, it’s the task of the compiler to decide which method has to be invoked based on the type of object used to invoke the method.

For example, ecobike.fuel() will invoke the fuel() method of the bicycle class and ebike.fuel() will invoke the fuel() method of the electric_bike class. We append all these objects to a list and in every iteration, we are going to call the same function names but the type of object which invokes the method is going to change. In the first iteration methods of the bicycle class is called, and methods of electric_bike, petrol_bike in further iterations.

upGrad’s Exclusive Data Science Webinar for you –

Watch our Webinar on The Future of Consumer Data in an Open Data Economy

 

 

background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree18 Months
View Program

Placement Assistance

Certification8-8.5 Months
View Program

Conclusion

In this article, we’ve understood what polymorphism means, discussed how python is different in the case of method overloading. Walked through demonstrations of various possibilities of polymorphism in pythons such as operator overloading, function polymorphism, method overriding, and polymorphism in class methods.

Now that you are aware of polymorphism in python, implement your next python code using all these features!

If you are curious to learn about data science, check out IIIT-B & upGrad’s PG Diploma in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Rohit Sharma

694 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months

View Program
Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

18 Months

View Program
upGrad Logo

Certification

3 Months

View Program