设计一个动物声音模拟器,希望模拟许多动物叫声
时间: 2024-06-13 18:06:13 浏览: 177
以下是一个设计动物声音模拟器的示例代码:
```python
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def cry(self):
pass
@abstractmethod
def getAnimalName(self):
pass
class Dog(Animal):
def cry(self):
return "汪汪汪"
def getAnimalName(self):
return "狗"
class Cat(Animal):
def cry(self):
return "喵喵喵"
def getAnimalName(self):
return "猫"
class AnimalSoundPlayer:
def playSound(self, animal):
print(animal.getAnimalName() + "发出了声音:" + animal.cry())
# 创建动物声音模拟器
player = AnimalSoundPlayer()
# 模拟狗叫声
dog = Dog()
player.playSound(dog)
# 模拟猫叫声
cat = Cat()
player.playSound(cat)
```
运行以上代码,将输出以下结果:
```
狗发出了声音:汪汪汪
猫发出了声音:喵喵喵
```
阅读全文