Animal Sounds with Polymorphism

Define a base class Animal with a method sound(). Implement child classes Dog, Cat, and Bird that override the sound() method to print the respective animal’s sound.

Example 1:

Input: Dog 
Output: "Woof!"

Example 2:

Input: Bird
Output: "Chirp!"

Override the sound() method in each subclass to return the sound of the animal.

class Animal:
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "Woof!"

class Cat(Animal):
    def sound(self):
        return "Meow!"

class Bird(Animal):
    def sound(self):
        return "Chirp!"

# Test the classes
dog = Dog()
print(dog.sound())  # Output: Woof!

bird = Bird()
print(bird.sound())  # Output: Chirp!

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!