Polymorphism and Inheritance in Python
Polymorphism and inheritance in Python are two fundamental concepts in object-oriented programming (OOP) that play a crucial role in Python. Let's explore each concept individually and then discuss how they can be combined in Python.
1. Inheritance:
Definition: Inheritance is a mechanism that allows a new class (subclass/derived class) to inherit attributes and behaviors from an existing class (base class/parent class). It promotes code reuse and the creation of a hierarchy of classes.
Example:
pythonCopy codeclass Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass # Abstract method, to be overridden in subclasses
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Usage
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Output: Buddy says Woof!
print(cat.speak()) # Output: Whiskers says Meow!
In this example, Dog
and Cat
inherit from the Animal
class, sharing the name
attribute and overriding the speak
method to provide their own implementation.
2. Polymorphism:
Definition: Polymorphism refers to the ability of a class to take on multiple forms. In Python, polymorphism is often achieved through method overriding. It allows objects of different classes to be treated as objects of a common base class.
Example:
pythonCopy codeclass Shape:
def area(self):
pass # Abstract method, to be overridden in subclasses
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
# Usage
circle = Circle(5)
rectangle = Rectangle(4, 6)
print(circle.area()) # Output: 78.5
print(rectangle.area()) # Output: 24
Here, Circle
and Rectangle
are subclasses of Shape
. Both classes implement the area
method differently, demonstrating polymorphism. Regardless of the specific class type, the area
method can be called on any object of the Shape
class.
3. Polymorphism and Inheritance Combined:
pythonCopy code# Continuing from the previous examples
# Polymorphism in action
shapes = [circle, rectangle]
for shape in shapes:
print(f"Area: {shape.area()}")
In this example, a list of shapes (instances of Circle
and Rectangle
) is created. The area
method is called on each shape, showcasing polymorphism. Each shape, regardless of its specific type, can be treated as an object of the common base class (Shape
) and exhibit its own behavior.
In Python, the combination of polymorphism and inheritance allows for flexible and modular code design, facilitating the creation of reusable and extensible software components.