Greetings! In today's lesson, we'll unravel the concept of polymorphism in Python's Object-Oriented Programming (OOP). Grasping polymorphism enables us to use a single entity (a method, class, or interface) to represent different types in various scenarios. Let's proceed.
Polymorphism, a pillar of OOP, allows one object to embody multiple forms. Visualize a button in software; depending on its type (for instance, a submit button or a radio button), the action resulting from pressing it varies. This dynamic encapsulates the spirit of polymorphism!
Let's observe polymorphism in action within a simple application involving shapes. The base Shape
class has an area
method, which calculates the area for shapes. This method is uniquely implemented in the subclasses Rectangle
and Circle
.
Python1class Shape: 2 def area(self): 3 pass 4 5class Rectangle(Shape): 6 def __init__(self, length, width): 7 self.length = length 8 self.width = width 9 10 def area(self): # calculate rectangle area 11 return self.length * self.width 12 13class Circle(Shape): 14 def __init__(self, radius): 15 self.radius = radius 16 17 def area(self): # calculate circle area 18 return 3.14 * self.radius * self.radius 19 20rectangle = Rectangle(2, 3) 21print(rectangle.area()) # Prints: 6 22 23circle = Circle(5) 24print(circle.area()) # Prints: 78.5
Here, polymorphism shines as the area
function takes on multiple forms and behaves differently depending on whether it's part of a Rectangle
or a Circle
.
Polymorphism is indispensable when dealing with inheritance, as a single action can exhibit different behaviors for different object types, streamlining the code while enhancing readability and maintainability.
Python supports various types of polymorphism. Dynamic polymorphism occurs during runtime and leverages method overriding within the base class. On the flip side, static polymorphism operates during compile time.
Below are illustrative examples of both types.
Python1class Shape: 2 def area(self, length=None, width=None, radius=None): 3 if radius: # If the radius is provided, calculate the circle area 4 return 3.14 * radius * radius 5 elif length and width: # if length and width are provided, calculate the rectangle area 6 return length * width 7 else: 8 return "Invalid parameters" 9 10shape = Shape() 11print(shape.area(length=5, width=2)) # Rectangle area 12print(shape.area(radius=3)) # Circle area
Great job! We've now learned about polymorphism, observed its implementation, and discovered its applications. Now, prepare for hands-on practice tasks. Apply what you've learned and excel in Python programming. Happy coding!