Python Polymorphism¶
Polymorphism = "Poly" + "morphism"
- "Poly" means Many
- "morphism" means combined form
Polymorphism simply means that we can call the same method name with different/same parameters, and depending on the parameters, it will do different things.
It can also be defined as follows
Polymorphism can be defined as different objects acts differently for same interface(i.e functions, methods, classes)
Let's look at an example
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
def print_area(shape):
print(f"type: {shape.__class__.__name__}")
print(f"area: {shape.area()}")
rect = Rectangle(10, 20)
print_area(rect)
# ouput:
# type: Rectangle
# area: 200
circle = Circle(10)
print_area(circle)
# ouput:
# type: Circle
# area: 314.0
- In the above code, we have two objects which are different types but has same method name
area()
- When we call area on method
area()
on each object it calculated differently and gave the output. - we can say
print_area
is a polymorphic function.
Note: we use method overloading & method overriding to achieve polymorphism in most of the cases.