Define a Pet class that stores the pet’s name, age, and weight. Add appropriate constructors, accessor, and mutator functions. Also define a function named getLifespan that returns a string with the value “unknown lifespan.” Next, define a Dog class that is derived from Pet. The Dog class should have a private member variable named breed that stores the breed of the dog. Add mutator and accessor functions for the breed variable and appropriate constructors. Redefine the getLifespan function to return "Approximately 7 years" if the dog’s weight is over 100 pounds and "Approximately 13 years" if the dog’s weight is under 100 pounds. Next, define a Rock class that is derived from Pet. Redefine the getLifespan function to return “Thousands of years”. Finally, write a test program that creates instances of pet rocks and pet dogs that exercise the inherited and redefined functions.
时间: 2024-03-18 15:41:02 浏览: 19
Sure! Here's an implementation of the Pet, Dog, and Rock classes with the requested functions:
```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 "unknown lifespan"
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.weight > 100:
return "Approximately 7 years"
else:
return "Approximately 13 years"
class Rock(Pet):
def getLifespan(self):
return "Thousands of years"
```
And here's a test program that creates instances of Pet, Dog, and Rock and exercises their inherited and redefined functions:
```python
# create some pets and dogs
pet1 = Pet("Fluffy", 3, 10)
pet2 = Pet("Spike", 5, 20)
dog1 = Dog("Rex", 2, 120, "German Shepherd")
dog2 = Dog("Fido", 8, 50, "Labrador Retriever")
# test the Pet class functions
print(pet1.getName()) # Fluffy
print(pet1.getAge()) # 3
print(pet1.getWeight()) # 10
pet1.setWeight(15)
print(pet1.getWeight()) # 15
print(pet1.getLifespan()) # unknown lifespan
# test the Dog class functions
print(dog1.getName()) # Rex
print(dog1.getBreed()) # German Shepherd
print(dog1.getLifespan()) # Approximately 7 years
print(dog2.getLifespan()) # Approximately 13 years
# test the Rock class functions
rock1 = Rock("Pebbles", 1000000, 1)
print(rock1.getLifespan()) # Thousands of years
```
I hope this helps! Let me know if you have any other questions.