All About Polymorphism in Python

All About Polymorphism in Python

5 mins read495 Views Comment
Updated on Feb 6, 2023 19:19 IST

In Python, polymorphism means the same function name is being used for different types. In this article, we will learn about polymorphism and how to use it with inheritance.

2023_01_MicrosoftTeams-image-119.jpg

In the world of object-oriented programming, polymorphism is a widely applied concept. Today, we are going to understand what polymorphism means, look at its different types and implement polymorphism in Python through examples. So, without further ado, let’s get started.

We will be covering the following sections today:

Introduction to OOPS

In layman’s terms, object-oriented programming is a methodology that focuses on an object or entity – basically, data – rather than functions and logic. Python is one of the most popular OOP languages among developers nowadays.

An important point to remember here is that every object is an instance of a class. Classes in OOP contain the attributes, or behavior, associated with a given object.

Suppose you visit a BMW car showroom. The showroom has different models of BMWs in different price ranges. So, even though they’re all BMWs, each of them has different attributes or features. This is what Polymorphism essentially is. The word ‘Polymorphism’ means having one name but many (poly) forms (morphs).

2023_01_image-43.jpg
Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

Polymorphism in Python

In object-oriented-based Python programming, Polymorphism means the same function name is being used for different types. Each function is differentiated based on its data type and number of arguments. So, each function has a different signature. This allows developers to write clean, readable, and resilient codes.

Let’s look at how Polymorphism is implemented in Python through simple examples:

Example 1: Function Polymorphism

 
friends = ['Joey', 'Rachel', 'Monica']
city = 'New York'
#calculate length
print(len(friends))
print(len(city))
Copy code

Output

2023_01_image-44.jpg

In the above example, we have used a built-in function len() that calculates the length of an object depending on its type. If the object is a list, the count of items within that list is returned. In the case of a string object, we get the count of characters in that string.

Thus, len() is a polymorphic built-in function as it goes by the same name but takes different types.

Example 2: Class Polymorphism

 
class Boy:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"My name is {self.name}. I am {self.age} years old.")
def gender(self):
print("M")
class Girl:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"My name is {self.name}. I am {self.age} years old.")
def gender(self):
print("F")
boy1 = Boy("Sam", 20)
girl1 = Girl("Mona", 26)
for person in (boy1, girl1):
person.gender()
person.info()
person.gender()
Copy code

Output:

2023_01_image-45.jpg

In the above example, we have created two classes – Boy and Girl with similar structures. They share the same function names – info() and gender().

Notice that even though we have not linked the two classes together, we can pack these two different objects into a tuple and iterate through it using a common variable person. This is allowed due to the concept of Polymorphism.

What is Programming What is Python
What is Data Science What is Machine Learning

How to Use Polymorphism?

Polymorphism can be achieved in two main ways:

  • Operator Overloading
  • Method Overloading

Let’s discuss both.

Operator Overloading

This is a type of overloading where an operator can be used in multiple ways beyond its predefined default behavior. In other words, the same operator can be used for different purposes.

Let’s understand through an example in Python:

 
num1 = 20
num2 = 10
print(num1+num2)
str1 = "Naukri"
str2 = "Learning"
print(str1+" "+str2)
Copy code

Output

2023_01_image-46.jpg

The above example shows that the ‘+’ operator performs arithmetic addition operations when used with integer data types. The same operator, however, performs concatenation when used with strings.

This is one of the simplest occurrences of Polymorphism in Python.

Method Overloading

This type of overloading means a class contains multiple methods with the same name but different arguments. Please note that Python does not support method overloading.

Polymorphism with Inheritance

As we have already understood, Polymorphism in Python allows us to define functions (methods) that are the same as functions in the parent classes.

Inheritance allows the functions of the parent class to be passed to the child class. In Python, it is possible to change a function that a child class has inherited from its parent class. This comes in handy when the inherited function from the parent is not required in the child class.

In such cases, we re-implement those functions in the child classes. This is known as Method Overriding. Let’s look at the following example for a better understanding:

 
class Animals:
def intro(self):
print("There are various species of animals in the world.")
def endangered(self):
print("Some species are endangered.")
class Whitetiger(Animals):
def endangered(self):
print("White tigers are endangered.")
class Monkey(Animals):
def endangered(self):
print("Monkeys are not endangered.")
animal1 = Animals()
whitetiger1 = Whitetiger()
monkey1 = Monkey()
animal1.intro()
animal1.endangered()
whitetiger1.intro()
whitetiger1.endangered()
monkey1.intro()
monkey1.endangered()
Copy code

Output:

2023_01_image-47.jpg

In the above example, we can see that the method endangered(), which has been derived from the parent class, has been overridden in the child classes.

This is another occurrence of Polymorphism in Python.

Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Duck Typing

Polymorphism enables an entity to be used as a general category for different purposes. The specific purpose is determined by the exact nature of the situation.

Duck typing is a concept of Polymorphism. It is basically a form of abductive reasoning that “if it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck”. In other words, if an object matches certain behavior of a category, then it will be considered an object of that category only.

Need for Polymorphism

Polymorphism enables developers to write a function that can correctly process different functionalities having the same name. As discussed, it allows performing one action in various ways depending upon the situation. This is quite an important feature in software development. Polymorphism commonly comes up when talking about loose coupling, dependency injection, interface, etc. However, these concepts are beyond the scope of this article.

Conclusion

Polymorphism is a critical concept one needs to understand when working on object-oriented programming. Hope this article was helpful for you to understand Polymorphism in Python.

Contributed by – Prerna Singh

Top Trending Article

Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python

Interview Questions

Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio