Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconWhat is Polymorphism in Python? Polymorphism Explained with Examples

What is Polymorphism in Python? Polymorphism Explained with Examples

Last updated:
4th Mar, 2021
Views
Read Time
5 Mins
share image icon
In this article
Chevron in toc
View All
What is Polymorphism in Python? Polymorphism Explained with Examples

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.

Explore our Popular Data Science Certifications

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

Top Data Science Skills to Learn

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

Read our popular Data Science Articles

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.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Explore Free Courses

Suggested Blogs

Data Science for Beginners: A Comprehensive Guide
5015
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5020
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5036
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Inheritance in Python | Python Inheritance [With Example]
17105
Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-
Read More

by Rohan Vats

27 Feb 2024

Data Mining Architecture: Components, Types & Techniques
10585
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
79399
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

19 Feb 2024

Sorting in Data Structure: Categories & Types [With Examples]
137481
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

Data Science Vs Data Analytics: Difference Between Data Science and Data Analytics
67767
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right
Read More

by Rohit Sharma

19 Feb 2024

13 Exciting Python Projects on Github You Should Try Today [2023]
44751
Python is one of the top choices in programming languages among professionals worldwide. Its straightforward syntax allows software developers and dat
Read More

by Hemant

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon