Python polymorphism
Python Polymorphism
The term “polymorphism” refers to a function or method that takes on different forms in different contexts. Because Python is a dynamically typed language, implementing polymorphism is very easy.
If a method in a parent class is overridden by different child classes with different business logic, the base class method is a polymorphic method.
Example
The following is an example of polymorphism. We have an abstract class, Shape, which serves as the parent class of two classes, Circle and Rectangle. These two classes override the parent class’s Draw() method in different ways.
from abc import ABC, abstractmethod
class shape(ABC):
@abstractmethod
def draw(self):
"Abstract method"
return
class circle(shape):
def draw(self):
super().draw()
print ("Draw a circle")
return
class rectangle(shape):
def draw(self):
super().draw()
print ("Draw a rectangle")
return
shapes = [circle(), rectangle()]
for shp in shapes:
shp.draw()
Output
When you run this code, the following output is produced:
Draw a circle
Draw a rectangle
The variable shp first references the Circle object and calls the draw() method of the Circle class. In the next iteration, it references the Rectangle object and calls the draw() method of the Rectangle class. Therefore, the draw() method in the Shape class is polymorphic.