这个题目要求完成父类和子类的定义,并完成测试。(总共20分) (1)定义动物类animal,在类中定义属性和方法: 我拥有属性sex,表示性别,数据类型为boolean; 我拥有属性age,表示年龄,数据类型为整数; (2)定义子类cat和dog,它们继承于animal类,重写一些属性和方法: cat类: 我是猫的子类,我拥有属性name,表示名字,数据类型为字符串,在子类中定义; 我拥有属性weight,表示体重,数据类型为小数,在子类中定义; 我重写了方法show,该方法用于显示猫的信息,包括introduce()的基本信息和子类特有的属性信息。 dog类: 我是狗的子类,我拥有属性breed,表示品种,数据类型为字符串,在子类中定义; 我拥有属性color,表示颜色,数据类型为字符串,在子类中定义; 我重写了方法show,该方法用于显示狗的信息,包括introduce()的基本信息和子类特有的属性信息。 (3)完成测试: 测试代码中,实例化一个猫对象和一个狗对象,分别调用它们的introduce()和show()方法,以检查定义的类是否正确。
时间: 2024-04-06 20:30:16 浏览: 134
好的,我知道了。下面是代码实现和测试:
```python
class Animal:
def __init__(self, sex, age):
self.sex = sex
self.age = age
def introduce(self):
print(f"I am an animal. My sex is {self.sex} and my age is {self.age}.")
class Cat(Animal):
def __init__(self, sex, age, name, weight):
super().__init__(sex, age)
self.name = name
self.weight = weight
def show(self):
print(f"My name is {self.name}. My weight is {self.weight}.")
self.introduce()
class Dog(Animal):
def __init__(self, sex, age, breed, color):
super().__init__(sex, age)
self.breed = breed
self.color = color
def show(self):
print(f"My breed is {self.breed}. My color is {self.color}.")
self.introduce()
cat = Cat(True, 3, "Kitty", 4.5)
dog = Dog(False, 5, "Golden Retriever", "Golden")
cat.introduce()
cat.show()
dog.introduce()
dog.show()
```
输出结果如下:
```
I am an animal. My sex is True and my age is 3.
My name is Kitty. My weight is 4.5.
I am an animal. My sex is True and my age is 3.
I am an animal. My sex is False and my age is 5.
My breed is Golden Retriever. My color is Golden.
I am an animal. My sex is False and my age is 5.
```
阅读全文