Polymorphism in collections refers to using different object types that implement a common interface within a single collection, such as a list or a set. This allows for flexible and reusable code, as operations can be performed on various objects without knowing their exact types.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class Bird(Animal):
def speak(self):
return "Tweet!"
animals = [Dog(), Cat(), Bird()]
for animal in animals:
print(animal.speak())
Woof!
Meow!
Tweet!
Dog, Cat, Bird) inherits from Animal and implements the speak method.Animal objects is created.speak method is called, demonstrating polymorphism.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 Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
shapes = [Circle(5), Square(4)]
for shape in shapes:
print(f"Area: {shape.area()}")
Area: 78.5
Area: 16