Polymorphism in Python with EXAMPLES
What is Polymorphism?
Polymorphism can be defined as a condition that occurs in many different forms. It is a concept in Python programming wherein an object defined in Python can be used in different ways. It allows the programmer to define multiple methods in a derived class, and it has the same name as present in the parent class. Such scenarios support method overloading in Python.
Polymorphism in Operators
An operator in Python helps perform mathematical and several other programming tasks. For example, the ‘+’ operator helps in performing addition between two integer types in Python, and in the same way, the same operator helps in concatenating strings in Python programming.
Let us take an example of + (plus) operator in Python to display an application of Polymorphism in Python as shown below:
Python Code:
p = 55 q = 77 r = 9.5 g1 = "Guru" g2 = "99!" print("the sum of two numbers",p + q) print("the data type of result is",type(p + q)) print("The sum of two numbers",q + r) print("the data type of result is", type (q + r)) print("The concatenated string is", g1 + g2) print("The data type of two strings",type(g1 + g2))
Output:
the sum of two numbers 132 the data type of result is <class 'int'> The sum of the two numbers 86.5 the data type of result is <class 'float'> The concatenated string is Guru99! The data type of two strings <class 'str'>
The above example can also be regarded as the example of operator overloading.
Polymorphism in user-defined methods
A user-defined method in the Python programming language are methods that the user creates, and it is declared using the keyword def with the function name.
Polymorphism in the Python programming language is achieved through method overloading and overriding. Python defines methods with def keyword and with the same name in both child and parent class.
Let us take the following example as shown below: –
Python Code:
from math import pi class square: def __init__(self, length): self.l = length def perimeter(self): return 4 * (self.l) def area(self): return self.l * self.l class Circle: def __init__(self, radius): self.r = radius def perimeter(self): return 2 * pi * self.r def area(self): return pi * self.r * * 2 # Initialize the classes sqr = square(10) c1 = Circle(4) print("Perimeter computed for square: ", sqr.perimeter()) print("Area computed for square: ", sqr.area()) print("Perimeter computed for Circle: ", c1.perimeter()) print("Area computed for Circle: ", c1.area())
Output:
Perimeter computed for square: 40 Area computed for square: 100 Perimeter computed for Circle: 25.132741228718345 Area computed for Circle: 50.26548245743669
In the above code, there are two user-defined methods, perimeter and area, defined in circle and square classes.
As shown above, both circle class and square class invoke the same method name displaying the characteristic of Polymorphism to deliver the required output.
Polymorphism in Functions
The built-in functions in Python are designed and made compatible to execute several data types. In Python, Len()
is one of the key built-in functions.
It works on several data types: list, tuple, string, and dictionary. The Len () function returns definite information aligned with these many data types.
The following figure shows how Polymorphism can be applied in Python with relation to in-built functions: –
Following program helps in illustrating the application of Polymorphism in Python: –
Python Code:
print ("The length of string Guru99 is ",len("Guru99")) print("The length of list is ",len(["Guru99","Example","Reader"])) print("The length of dictionary is ",len({"Website name":"Guru99","Type":"Education"}))
Output:
The length of string Guru99 is 6 The length of the list is 3 The length of the dictionary is 2
In the above example, Len () function of Python performs Polymorphism for string, list, and dictionary data types, respectively.
Polymorphism and Inheritance
Inheritance in Python can be defined as the programming concept wherein a child class defined inherit properties from another base class present in Python.
There are two key Python concepts termed method overriding and method overloading.
- In method overloading, Python provides the feature of creating methods that have the same name to perform or execute different functionalities in a given piece of code. It allows to overload methods and uses them to perform different tasks in simpler terms.
- In Method overriding, Python overrides the value that shares a similar name in parent and child classes.
Let us take the following example of Polymorphism and inheritance as shown below: –
Python Code:
class baseclass: def __init__(self, name): self.name = name def area1(self): pass def __str__(self): return self.name class rectangle(baseclass): def __init__(self, length, breadth): super().__init__("rectangle") self.length = length self.breadth = breadth def area1(self): return self.length * self.breadth class triangle(baseclass): def __init__(self, height, base): super().__init__("triangle") self.height = height self.base = base def area1(self): return (self.base * self.height) / 2 a = rectangle(90, 80) b = triangle(77, 64) print("The shape is: ", b) print("The area of shape is", b.area1()) print("The shape is:", a) print("The area of shape is", a.area1())
Output:
The shape is: a triangle The area of a shape is 2464.0 The shape is: a rectangle The area of a shape is 7200
In above code, the methods have the same name defined as init method and area1 method. The object of class square and rectangle are then used to invoke the two methods to perform different tasks and provide the output of the area of square and rectangle.
Polymorphism with the Class Methods
The Python programming enables programmers to achieve Polymorphism and method overloading with class methods. The different classes in Python can have methods that are declared in the same name across the Python code.
In Python, two different classes can be defined. One would be child class, and it derives attributes from another defined class termed as parent class.
The following example illustrates the concept of Polymorphism with class methods: –
Python Code:
class amazon: def __init__(self, name, price): self.name = name self.price = price def info(self): print("This is product and am class is invoked. The name is {self.name}. This costs {self.price} rupees.") class flipkart: def __init__(self, name, price): self.name = name self.price = price def info(self): print(f "This is product and fli class is invoked. The name is {self.name}. This costs {self.price} rupees.") FLP = flipkart("Iphone", 2.5) AMZ = amazon("Iphone", 4) for product1 in (FLP, AMZ): product1.info()
Output:
This is a product, and fli class is invoked. The name is iPhone, and this costs 2.5 rupees. This is a product, and am class is invoked. The name is iPhone, and this costs 4 rupees.
In the above code, two different classes named as flipkart and amazon use the same method names info and init to provide respective price quotations of the product and further illustrate the concept of Polymorphism in Python.
Difference between Method overloading and compile-time Polymorphism
In compile-time Polymorphism, the compiler of the Python program resolves the call. Compile-time Polymorphism is accomplished through method overloading.
The Python compiler does not resolve the calls during run time for polymorphism. It is also classified as method overriding wherein the same methods carry similar signatures or properties, but they form a part of different classes.
Summary
- Polymorphism can be defined as a condition that occurs in many different forms.
- An operator in Python helps perform mathematical and several other programming tasks.
- A user-defined method in the Python programming language are methods that the user creates, and it is declared using the keyword def with the function name.
- Polymorphism in Python offers several desirable qualities, such as it promotes the reusability of codes written for different classes and methods.
- A child class is a derived class, and it gets its attributes from the parent class.
- The Polymorphism is also achieved through run-time method overriding and compile-time method overloading.
- Polymorphism in Python is also attained through operator overloading and class methods.