10. 编写一个程序,定义一个Animal类,包含属性name和age,以及一个eat()方法。然后定义一个Cat类和一个Dog类继承Animal类,并分别实现它们自己的eat()方法。在主函数中创建一个Cat对象和一个Dog对象,并分别调用它们的eat()方法。
时间: 2024-03-12 15:50:03 浏览: 138
好的,以下是您所要求的Python代码:
```python
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(f"{self.name} is eating.")
class Cat(Animal):
def eat(self):
print(f"{self.name} is eating fish.")
class Dog(Animal):
def eat(self):
print(f"{self.name} is eating meat.")
cat = Cat("Tom", 3)
dog = Dog("Max", 5)
cat.eat()
dog.eat()
```
在上述代码中,我们首先定义了一个Animal类,该类有一个构造函数,接受参数name和age,并且有一个eat()方法,用于打印出该动物正在吃东西的信息。接下来,我们定义了一个Cat类和一个Dog类,它们都继承自Animal类,并且分别重写了eat()方法。在主函数中,我们创建了一个Cat对象和一个Dog对象,并分别调用它们的eat()方法。输出结果应该如下所示:
```
Tom is eating fish.
Max is eating meat.
```
相关问题
1.ES6定义一个类(函数内部定义属性,,原型定义方法 ), 实现继承?
可以使用ES6的class语法来定义一个类,并使用extends关键字实现继承。在类内部使用constructor方法定义属性,使用prototype定义方法。
例如,定义一个Animal类,包含name和age属性,和eat方法:
```
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat(food) {
console.log(`${this.name} is eating ${food}.`);
}
}
```
然后定义一个继承自Animal的Cat类,包含color属性,和meow方法:
```
class Cat extends Animal {
constructor(name, age, color) {
super(name, age);
this.color = color;
}
meow() {
console.log(`${this.name} is meowing.`);
}
}
```
在Cat类中使用super关键字调用父类的constructor方法,继承父类的属性和方法。然后定义自己的属性和方法。
这样,就可以创建一个Cat对象,并调用其继承自Animal的属性和方法:
```
let myCat = new Cat("Kitty", 2, "black");
myCat.eat("fish"); // output: Kitty is eating fish.
myCat.meow(); // output: Kitty is meowing.
```
.定义一个动物类 Animal
以下是一个简单的动物类 Animal 的定义:
```python
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(f"{self.name} is eating.")
def sleep(self):
print(f"{self.name} is sleeping.")
```
这个类有两个属性 `name` 和 `age`,以及两个方法 `eat()` 和 `sleep()`。我们可以通过创建实例来表示不同的动物,例如:
```python
dog = Animal("Buddy", 3)
cat = Animal("Whiskers", 5)
dog.eat() # 输出 "Buddy is eating."
cat.sleep() # 输出 "Whiskers is sleeping."
```
这个类只是一个基础的示例,你可以根据需要添加更多的属性和方法来扩展它。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)