Complete Dog and Cat so that each overrides speak(): dogs say Woof and cats say Meow. The program prints one line per animal.
What to build
Two child classes that each replace one method.
Requirements
- Complete
DogandCat, each overridingspeak(). - Leave the rest of the program as it is.
Input
The first line has n (1 to 50). Each of the next n lines is dog NAME or cat NAME.
Output
For each animal: NAME says SOUND.
Constraints
n is from 1 to 50.
Example
Input:
2
dog Tommy
cat Mini
Output:
Tommy says Woof
Mini says Meow
Why it works
The main loop calls the same method for every animal, and each object answers according to its own class.
Examples
Example 1 · Input
2 dog Tommy cat Mini
Expected output
Tommy says Woof Mini says Meow
Example 2 · Input
1 cat Kitty
Expected output
Kitty says Meow
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Define speak inside Dog and inside Cat; each replaces Animal's version.
Solution
Show one correct solution (try it yourself first)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
n = int(input())
for _ in range(n):
kind, name = input().split()
pet = Dog(name) if kind == "dog" else Cat(name)
print(pet.name, "says", pet.speak())