Polymorphism in object-oriented programming allows objects of different classes to be treated as objects of a common type. This means you can write functions that work with objects of various types without needing to know their specific type at compile time.
class Animal:
def speak(self):
print("Generic animal sound")
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
animals = [Dog("Buddy"), Cat("Whiskers")]
for animal in animals:
animal.speak() # Output: Woof! and Meow!
Here, both Dog
and Cat
have a speak
method. The `animal.speak()` call dynamically invokes the correct version of the method based on the object's type at runtime.
def animal_sound(animal):
animal.speak()
animal_sound(Dog("Rover")) # Output: Woof!
animal_sound(Cat("Mittens")) # Output: Meow!
The `animal_sound` function can accept any `Animal`-type object without knowing its specific class.
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius * self.radius
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(shape.area()) # Output: areas of each shape
This example illustrates polymorphism with a `Shape` base class and derived classes `Circle` and `Rectangle`. The `area()` method is defined differently in each, yet the same function call (`shape.area()`) works for different shape types.