All function calls work correctly because Python is a dynamically typed language. The interpreter chooses the correct implementation of the operation +.
Consider an example of programming code that contains two classes: Circle() and Square(). Each class has methods for measuring area and perimeter.
from math import pi
class Circle:
def __init__(self, radius): # initialize one attribute radius
self.radius = radius
def area(self):
return pi * self.radius ** 2
def perimeter(self):
return 2 * pi * self.radius
class Square:
def __init__(self, side): # initialize one attribute side
self.side = side
def area(self):
return self.side * self.side
def perimeter(self):
return 4 * self.side
def print_shape_info(shape): # polymorphic function for displaying the area and perimeter of a shape
print(f"Area = {shape.area()}, perimeter = {shape.perimeter()}.")
# create an instance square
square = Square(2)
print_shape_info(square) # Area = 4, perimeter = 8. # create an instance circle
circle = Circle(5)
print_shape_info(circle) # Area = 78.53981633974483, perimeter = 31.41592653589793.
Questions:
Explain the term "polymorphism".
Give an example of polymorphism in real life.
How to find out by the class name what methods it implements?