定义一个宠物类来存储宠物的名字、年龄和体重。添加适当的构造函数、访问器和mutator函数。还要定义一个名为getLifespan的函数,它返回一个值为“未知寿命”的字符串。 接下来,定义一个派生自Pet的Dog类。Dog类应该有一个名为breed的私有成员变量,用于存储狗的品种。为breed变量和适当的构造函数添加mutator和accessor函数。重新定义getLifespan函数,如果狗的体重超过100磅,则返回“大约7年”和“大约”
时间: 2024-03-18 16:41:16 浏览: 170
以下为Python代码实现:
```python
# 宠物类
class Pet:
def __init__(self, name, age, weight):
self.__name = name
self.__age = age
self.__weight = weight
def getName(self):
return self.__name
def getAge(self):
return self.__age
def getWeight(self):
return self.__weight
def setName(self, name):
self.__name = name
def setAge(self, age):
self.__age = age
def setWeight(self, weight):
self.__weight = weight
def getLifespan(self):
return "未知寿命"
# 狗类
class Dog(Pet):
def __init__(self, name, age, weight, breed):
super().__init__(name, age, weight)
self.__breed = breed
def getBreed(self):
return self.__breed
def setBreed(self, breed):
self.__breed = breed
def getLifespan(self):
if self.getWeight() > 100:
return "大约7年"
else:
return "大约" + super().getLifespan()
# 测试代码
dog = Dog("旺财", 3, 120, "藏獒")
print(dog.getName())
print(dog.getAge())
print(dog.getWeight())
print(dog.getBreed())
print(dog.getLifespan())
dog.setWeight(80)
print(dog.getLifespan())
```
运行结果为:
```
旺财
3
120
藏獒
大约7年
大约未知寿命
```
阅读全文