Abstract Base Classes
Completed
Using abc.ABC, create an abstract Animal with an abstract method sound(). Create Cat and Cow. Trying to create an Animal must fail. Read animal names and print NAME: SOUND, or cannot create Animal for Animal.
Input
One line of names (Cat, Cow, Animal).
Output
One line per name.
Example
Input
Cat Cow Animal
Output
Cat: meow Cow: moo cannot create Animal
Editor
Python
Hints
Instantiating a class with unimplemented abstract methods raises TypeError.
Solution explanation
Abstract base classes define an interface that subclasses must implement.
Show solution
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
...
class Cat(Animal):
def sound(self):
return "meow"
class Cow(Animal):
def sound(self):
return "moo"
classes = {"Cat": Cat, "Cow": Cow, "Animal": Animal}
for name in input().split():
try:
print(f"{name}: {classes[name]().sound()}")
except TypeError:
print("cannot create Animal")