Polymorphism
In object-oriented programming (OOP), polymorphism refers to the ability of different objects to respond to the same method call in different ways.
There are two main types of polymorphism in OOP:
Method polymorphism: This refers to the ability of different objects to respond to the same method call in different ways, depending on the type of the object. This can be achieved through inheritance and method overriding.
Operator polymorphism: This refers to the ability of different objects to respond to the same operator (such as +, -, *, etc.) in different ways, depending on the type of the object. This can be achieved through operator overloading.
In Python, method polymorphism can be achieved through inheritance and method overriding. When a subclass (a class that is derived from another class) overrides a method of its superclass (the class from which it is derived), the subclass's method will be called instead of the superclass's method when the method is called on an instance of the subclass.
Here is an example of method polymorphism in Python through inheritance and method overriding:
class Shape:
def area(self):
pass # this method will be overridden in the subclass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius**2
rectangle = Rectangle(10, 20)
circle = Circle(5)
print(rectangle.area()) # Output: 200
print(circle.area()) # Output: 78.5
In this example, the Rectangle and Circle classes