OOPs

Polymorphism in Python (with Examples)

Polymorphism in Python is an important topic in Object-oriented programming. Assume there is a person who can have many qualities or relationships at the same time. As in, the person is a father, a brother, a husband, and an employee all at the same time. As a result, the same person exhibits diverse behavior in different settings. This is known as polymorphism. In this tutorial, we’ll look at what polymorphism in Python is and how it works. We’ll also learn how to use it in our own Python programs.

What is Polymorphism?

Polymorphism is defined as the circumstance of occurring in several forms. It refers to the usage of a single type entity (method, operator, or object) to represent several types in various contexts. Polymorphism is made from 2 words – ‘poly‘ and ‘morphs.’ The word ‘poly’ means ‘many’ and ‘morphs’ means ‘many forms.’ Polymorphism, in a nutshell, means having multiple forms. To put it simply, polymorphism allows us to do the same activity in a variety of ways.

Polymorphism has the following advantages:

  • It is beneficial to reuse the codes.
  • The codes are simple to debug.
  • A single variable can store multiple data types.

Polymorphism may be used in one of the following ways in an object-oriented language:

  • Overloading of operators
  • Class Polymorphism in Python
  • Method overriding, also referred to as Run time Polymorphism
  • Method overloading, also known as Compile time Polymorphism

Polymorphism is supported in Python via method overriding and operator overloading. However, Python does not support method overloading in the classic sense.

Polymorphism in Python through Operator Overloading

Operator overloading is another type of polymorphism in which the same operator performs various operations depending on the operands. Python allows for operator overloading. Let us look at a few built-in Polymorphism in Python examples below:

  1. Polymorphism in + operator:

We already know that the ‘+’ operator is frequently used in Python programs. However, it does not have a single application. When you wish to add two integers, concatenate two strings, or extend two lists, you use the same + sign. The + operator behaves differently depending on the type of object on which it is used.

Example

                    
a = 10
b = 20
print('Addition of 2 numbers:', a + b)

str1 = 'Hello '
str2 = 'Python'
print('Concatenation of 2 strings:', str1 + str2)

list1 = [1, 2, 3]
list2 = ['A', 'B']
print('Concatenation of 2 lists:', list1 + list2)

Output

                    
Addition of 2 numbers: 30
Concatenation of 2 strings: Hello Python
Concatenation of 2 lists: [1, 2, 3, 'A', 'B']

The + operator is used to execute arithmetic addition on integer data types. Similarly, the + operator is used to execute concatenation on string data types. In the case of lists, it returns a new list that contains elements from both original lists.

  1. Polymorphism in * operator:

The * operator is used to multiply 2 numbers if the data elements are numeric values. If one of the data types is a string, and the other is numeric, the string is printed that many times as that of the 2nd variable in the multiplication process.

Example

                    
a = 10
b = 5
print('Multiplication of 2 numbers:', a * b)

num = 3
mystr = 'Python'
print('Multiplication of string:', num * mystr)

Output

                    
Multiplication of 2 numbers: 50
Multiplication of string: PythonPythonPython

Function Polymorphism in Python

There are certain Python functions that can be used with different data types. The len() function is one example of such a function. Python allows it to work with a wide range of data types.

The built-in function len() estimates an object’s length based on its type. If an object is a string, it returns the number of characters; or if an object is a list, it returns the number of elements in the list. If the object is a dictionary, it gives the total number of keys found in the dictionary.

Example

                    
mystr = 'Programming'
print('Length of string:', len(mystr))

mylist = [1, 2, 3, 4, 5]
print('Length of list:', len(mylist))

mydict = {1: 'One', 2: 'Two'}
print('Length of dict:', len(mydict))

Output

                    
Length of string: 11
Length of list: 5
Length of dict: 2

Class Polymorphism in Python

Because Python allows various classes to have methods with the same name, we can leverage the concept of polymorphism when constructing class methods. We may then generalize calling these methods by not caring about the object we’re working with. Then we can write a for loop that iterates through a tuple of items.

Example

                    
class Tiger():
    def nature(self):
        print('I am a Tiger and I am dangerous.')

    def color(self):
        print('Tigers are orange with black strips')

class Elephant():
    def nature(self):
        print('I am an Elephant and I am calm and harmless')

    def color(self):
        print('Elephants are grayish black')

obj1 = Tiger()
obj2 = Elephant()

for animal in (obj1, obj2): # creating a loop to iterate through the obj1 and obj2
    animal.nature()
    animal.color()

Output

                    
I am a Tiger and I am dangerous.
Tigers are orange with black strips
I am an Elephant and I am calm and harmless
Elephants are grayish black

Explanation

We’ve created two classes here: Tiger and Elephant. They have the same structure and the same method names, nature() and color ().

However, you’ll see that we haven’t built a common superclass or connected the classes in any manner. Even so, we may combine these two objects into a tuple and iterate over it using a common animal variable. Because of polymorphism, it is conceivable.

Polymorphism and Inheritance (Method Overriding)

Polymorphism is most commonly associated with inheritance. In Python, child classes, like other programming languages, inherit methods and attributes from the parent class. Method Overriding is the process of redefining certain methods and attributes to fit the child class. This is especially handy when the method inherited from the parent class does not exactly fit the child class. In such circumstances, the method is re-implemented in the child class. Method Overriding refers to the technique of re-implementing a method in a child class.

Example

                    
class Vehicle:
    def __init__(self, brand, model, price):
        self.brand = brand
        self.model = model
        self.price = price

    def show(self):
        print('Details:', self.brand, self.model, 'Price:', self.price)

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

    def gear_system(self):
        print('Vehicle has 6 shifter gearbox')

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

    def gear_system(self):
        print('Car has Automatic Transmission')

# Car Object
car = Car('Audi', 'R8', 9000000)
car.show()
# call methods from Car class
car.max_speed()
car.gear_system()

# Vehicle Object
vehicle = Vehicle('Nissan', 'Magnite', 550000)
vehicle.show()
# call method from a Vehicle class
vehicle.max_speed()
vehicle.gear_system()

Output

                    
Details: Audi R8 Price: 9000000
Car max speed is 260
Car has Automatic Transmission

Details: Nissan Magnite Price: 550000
Vehicle max speed is 160
Vehicle has 6 shifter gearbox

As you can see, the Python interpreter detects that the car object’s max_speed() and gear_system() methods are overridden due to polymorphism. As a result, it employs the one defined in the child class (Car).

The show() function, on the other hand, has not been modified, i.e. it is not overridden in the Car class, hence it is utilized from the Vehicle class.

Compile-Time Polymorphism (Method Overloading)

Method overloading occurs when a class contains many methods with the same name. The types and amount of arguments passed by these overloaded methods vary. Python does not support method overloading or compile-time polymorphism. If there are multiple methods with the same name in a class or Python script, the method specified in the latter one will override the earlier one.

Python does not use function arguments in method signatures, hence method overloading is not supported.

Frequently Asked Questions

Q1. What is polymorphism in python?

Polymorphism is defined as the circumstance of occurring in several forms. It refers to the usage of a single type entity (method, operator, or object) to represent several types in various contexts. Polymorphism is made from 2 words – ‘poly‘ and ‘morphs.’ The word ‘poly’ means ‘many’ and ‘morphs’ means ‘many forms.’ Polymorphism, in a nutshell, means having multiple forms. To put it simply, polymorphism allows us to do the same activity in a variety of ways.

Assume there is a person who can have many qualities or relationships at the same time. As in, the person is a father, a brother, a husband, and an employee all at the same time. As a result, the same person exhibits diverse behavior in different settings. This is known as polymorphism.

Q2. Why do we need polymorphism?

Objects in object-oriented programming must take several shapes. This characteristic is very useful in software development. A single action can be done in multiple ways because to polymorphism. This notion is frequently used while discussing loose coupling, dependency injection, and interfaces, among other things. Polymorphism has the following advantages:

  • It is beneficial to reuse the codes.
  • The codes are simple to debug.
  • A single variable can store multiple data types.
Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Browse

OOPs
  • Polymorphism in Python (with Examples)

Leave a Reply

avatar
  Subscribe  
Notify of

Browse

OOPs
  • Polymorphism in Python (with Examples)

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

Which class are you in?
No thanks.