Polymorphism in Python
What is polymorphism and why is it important?
Polymorphism's literal definition is the state of occurring in diverse shapes or forms.
When it comes to programming, the idea of polymorphism is crucial. Using a same type entity (method, operator, or object) to represent multiple types in various contexts is known as polymorphism.
How about the following example:
A polymorphism in the addition operator as an example
The Plus operator is widely used in Python applications, as we all know. However, it has no one use.
+ Operator is used for integer data types to perform arithmetic addition.
SYNTAX
num1 = 1 num2 = 2 print(num1+num2)
This is why program produces 3 in this case.
Concatenation is performed using the + operator for string data types.
SYNTAX
str1 = "Python" str2 = "Programming" print(str1+" "+str2)
Python Programming is the consequence of the above code.
Using the + operator, we can observe that various operations have been performed on distinct data types. This is one of the simplest examples of polymorphism in Python that I've come across thus far.
Polymorphism of Python functions
Some Python functions may be used with a variety of data types.
len() is an example of such a function. Python allows you to execute it with a wide variety of data types. Let's have a look at a few examples of how the function may be used.
Function len() using polymorphism as an example
SYNTAX
print(len("Programiz")) print(len(["Python", "Java", "C"])) print(len({"Name": "John", "Address": "Nepal"}))
OUTPUT
9 3 2
We can see that the len() method can operate with a wide variety of data types, including text, list, tuple, set, and dictionary. On the other hand we can see that it only delivers information about particular data kinds.
Polymorphism of classes in the Python programming language
As far as object-oriented programming is concerned, polymorphism is a crucial notion.
Python Object-Oriented Programming is a great resource for learning more about OOP in Python.
Class methods can take use of polymorphism since Python enables distinct classes to have methods that have the same name. In the future, we may extend the use of these methods by not caring about the object we're dealing with. Let's have a look at a specific case:
Class Method Polymorphism next example
SYNTAX
class Cat: def __init__(self, name, age): self.name = name self.age = age def info(self): print(f"I am a cat. My name is {self.name}. I am {self.age} years old.") def make_sound(self): print("Meow") class Dog: def __init__(self, name, age): self.name = name self.age = age def info(self): print(f"I am a dog. My name is {self.name}. I am {self.age} years old.") def make_sound(self): print("Bark") cat1 = Cat("Kitty", 2.5) dog1 = Dog("Fluffy", 4) for animal in (cat1, dog1): animal.make_sound() animal.info() animal.make_sound()
Output:
Meow I am a cat. My name is Kitty. I am 2.5 years old. Meow Bark I am a dog. My name is Fluffy. I am 4 years old. Bark
There are two classes in this game: Cat and Dog. info() and make sound are identical in structure and have the same method names ().
Observe, however, that we haven't built a common superclass or connected the classes in any manner together. But even in that case, we may combine these two objects into one tuple and iterate through it using a common animal variable to keep track of the results. Polymorphism makes it feasible.
Polymorphism and Inheritance
Child classes inherit methods and properties from the parent class in Python, just as they do in most other programming languages. Method Overriding allows us to modify particular methods and properties explicitly for the child class.
As a result of polymorphism, we are able to access overridden methods and attributes that have the same name as their parent.
Let's have a look at a specific case:
from math import pi class Shape: def __init__(self, name): self.name = name def area(self): pass def fact(self): return "I am a two-dimensional shape." def __str__(self): return self.name class Square(Shape): def __init__(self, length): super().__init__("Square") self.length = length def area(self): return self.length**2 def fact(self): return "Squares have each angle equal to 90 degrees." class Circle(Shape): def __init__(self, radius): super().__init__("Circle") self.radius = radius def area(self): return pi*self.radius**2 a = Square(4) b = Circle(7) print(b) print(b.fact()) print(a.fact()) print(b.area())