Understanding Polymorphism in Python - How to Write Reusable Code
Polymorphism
is a concept in object-oriented programming that refers to the ability of a single function or method to operate on multiple types of data. In Python, polymorphism is achieved through the use of inheritance and interfaces.
One example of polymorphism in Python is through the use of inheritance. Let's say we have a class called "Animal" and two subclasses, "Dog" and "Cat". Both the Dog and Cat classes inherit from the Animals class, and therefore have access to any methods defined in the parent class.
class Animals:
def speak(self):
pass
class Dog(Animals):
def speak(self):
return "Woof!"
class Cat(Animals):
def speak(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!
As we can see in the above code, the speak method is defined in the parent class Animals and is overridden in the Dog and Cat class. And when we call the method on dog and cat object, it returns the respective output.
Another example of polymorphism in Python is through the use of interfaces. In Python, interfaces are not explicitly defined like in some other programming languages, but rather are implied through the use of specific methods. For example, let's say we have a class called "Shape" and two subclasses, "Circle" and "Rectangle". Both the Circle and Rectangle classes have a method called "area" which calculates the area of the shape.
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
circle = Circle(5)
rectangle = Rectangle(2, 4)
print(circle.area()) # Output: 78.5
print(rectangle.area()) # Output: 8
As we can see in the above code, the area method is defined in the parent class Shape and is overridden in the Circle and Rectangle class. And both class have same methods with different implementation.
In conclusion, polymorphism
is a powerful concept in object-oriented programming that allows for the creation of flexible and reusable code. In Python, it is achieved through the use of inheritance and interfaces, which allow for a single function or method to operate on multiple types of data.