使用 python 创建一个动物父类,创建牛和羊两个子类,根据输入的动物种类和名字输 出语句 输入:第一行输入”cow” or “sheep” 第二行输入他的名字 输出: “name”+” says "muu"” or” says "mee"”
时间: 2023-09-03 09:04:57 浏览: 77
### 回答1:
好的,请稍等一下。我已经用 Python 编写了动物父类和牛、羊两个子类,下面是完整的代码。
```python
class Animal:
def __init__(self, name):
self.name = name
class Cow(Animal):
def __init__(self, name):
super().__init__(name)
def sound(self):
return "muu"
class Sheep(Animal):
def __init__(self, name):
super().__init__(name)
def sound(self):
return "mee"
animal_type = input()
animal_name = input()
if animal_type == "cow":
cow = Cow(animal_name)
print(cow.name, "says", cow.sound())
elif animal_type == "sheep":
sheep = Sheep(animal_name)
print(sheep.name, "says", sheep.sound())
else:
print("Invalid animal type")
```
如果你输入 cow 和 Tom,会得到以下输出:
```
Tom says muu
```
如果你输入 sheep 和 Jerry,会得到以下输出:
```
Jerry says mee
```
希望这能够帮助你。
### 回答2:
以下是使用Python实现的代码。首先,创建一个Animal类作为动物的父类,其中包含一个名为animal_type的属性和一个名为speak的方法。然后,创建Cow类和Sheep类作为Animal类的子类,重写speak方法以根据不同的动物类型输出不同的语句。
```python
class Animal:
def __init__(self, animal_type):
self.animal_type = animal_type
def speak(self):
pass
class Cow(Animal):
def __init__(self, name):
super().__init__("cow")
self.name = name
def speak(self):
print(self.name, "says \"muu\"")
class Sheep(Animal):
def __init__(self, name):
super().__init__("sheep")
self.name = name
def speak(self):
print(self.name, "says \"mee\"")
# 主程序
animal_type = input()
name = input()
if animal_type == "cow":
cow = Cow(name)
cow.speak()
elif animal_type == "sheep":
sheep = Sheep(name)
sheep.speak()
```
使用以上代码,当输入为"cow"和"John"时,输出为"John says "muu" ";当输入为"sheep"和"Mary"时,输出为“Mary says "mee"”。
### 回答3:
以下是使用Python实现的代码:
```python
class Animal:
def __init__(self, name):
self.name = name
def say(self):
pass
class Cow(Animal):
def say(self):
return self.name + " says \"muu\""
class Sheep(Animal):
def say(self):
return self.name + " says \"mee\""
animal_type = input() # 输入动物种类
animal_name = input() # 输入动物名字
if animal_type == "cow":
animal = Cow(animal_name)
elif animal_type == "sheep":
animal = Sheep(animal_name)
else:
print("Invalid animal type")
print(animal.say())
```
通过上述代码,我们定义了一个`Animal`类作为动物的父类,包含一个`name`属性和一个`say`方法。牛和羊两个子类`Cow`和`Sheep`分别继承了`Animal`类,并重写了`say`方法。 `Cow`类的`say`方法输出`"muu"`,`Sheep`类的`say`方法输出`"mee"`。
然后,我们通过输入动物种类和名字来创建相应的动物对象,并调用其`say`方法来输出相应的语句。最后,我们将输出结果打印出来。