Polymorphism
The "Chirp and Tweet" problem is a simple programming exercise designed to illustrate polymorphism in object-oriented design. It requires creating an abstract base class called Bird with an unimplemented make_sound() method , and two subclasses, Sparrow and Parrot, which inherit from Bird and override the make_sound() method to print "Chirp Chirp" and "Tweet Tweet," respectively . The demonstration culminates with a BirdCage class containing a make_bird_sounds() method; this method accepts a list of Bird objects and, by iterating over them and calling make_sound(), demonstrates how the same method call yields different, appropriate results based on the object's true type (Sparrow or Parrot), which is the core principle of polymorphism.
main.py
from sparrow import Sparrow
from parrot import Parrot
from birdCage import BirdCage
def main():
birds = []
num = int(input("How many birds do you want to add? "))
for i in range(num):
print(f"\nBird {i+1}:")
btype = input("Enter bird type (sparrow/parrot): ").strip().lower()
color = input("Enter color: ")
age = int(input("Enter age: "))
if btype == "sparrow":
birds.append(Sparrow(color, age))
elif btype == "parrot":
birds.append(Parrot(color, age))
else:
print("Unknown bird type, skipping this one.")
if birds:
cage = BirdCage()
print("\nBird sounds:")
cage.make_bird_sounds(birds)
else:
print("No birds to display.")
if __name__ == "__main__":
main()
sparrow.py
from bird import Bird
class Sparrow(Bird):
def make_sound(self):
print("Chirp Chirp!")
parrot.py
from bird import Bird
class Parrot(Bird):
def make_sound(self):
print("Tweet Tweet!")
bairdCage.py
class BirdCage:
def make_bird_sounds(self, birds: list):
for bird in birds:
bird.make_sound()
bird.py
from abc import ABC, abstractmethod
class Bird(ABC):
def __init__(self, color, age, sound=""):
self.color = color
self.age = age
self.sound = sound
@abstractmethod
def make_sound(self):
print("Generic Bird Sound")
How many birds do you want to add: 3
Bird 1:
Enter bird type (sparrow/parrot): sparrow
Enter color: brown
Enter age: 2
Bird 2:
Enter bird type (sparrow/parrot): parrot
Enter color: green
Enter age: 3
Bird 3:
Enter bird type (sparrow/parrot): sparrow
Enter color: gray
Enter age: 1
Bird sounds:
Chirp Chirp!
Tweet Tweet!
Chirp Chirp!