创建动物类,其叫声为输出“叽里咕噜”,猫类,狗类,鸭类,鸡类继承动物类,分别发出叫声“喵喵”,“汪汪”,“嘎嘎”,“咯咯”,输入动物名,输出相应动物叫声,输出格式为“动物名 : 动物叫声\\n“
时间: 2023-04-26 21:00:10 浏览: 280
好的,以下是创建动物类,以及猫类、狗类、鸭类、鸡类的继承,以及输出相应叫声的代码:
```python
class Animal:
def __init__(self):
self.sound = "叽里咕噜"
def make_sound(self):
print(self.sound)
class Cat(Animal):
def __init__(self):
super().__init__()
self.sound = "喵喵"
class Dog(Animal):
def __init__(self):
super().__init__()
self.sound = "汪汪"
class Duck(Animal):
def __init__(self):
super().__init__()
self.sound = "嘎嘎"
class Chicken(Animal):
def __init__(self):
super().__init__()
self.sound = "咯咯"
# 测试代码
animal_name = input("请输入动物名:")
if animal_name == "猫":
cat = Cat()
print("猫 : " + cat.sound)
elif animal_name == "狗":
dog = Dog()
print("狗 : " + dog.sound)
elif animal_name == "鸭":
duck = Duck()
print("鸭 : " + duck.sound)
elif animal_name == "鸡":
chicken = Chicken()
print("鸡 : " + chicken.sound)
else:
animal = Animal()
print(animal_name + " : " + animal.sound)
```
希望能对您有所帮助!
阅读全文