编写程序,创建基类Animal,其成员包括实例属性color,实例方法getColor()和setColor()分别用来获取和设置color的值,实例方法 abilities()输出字符串“Animals can run”。创建派生类Dog,继承Animal类,新增实例属性name,新增实例方法getName()和setName()分别用来获取和设置name的值,重写基类的实例方法 abilities(),输出字符串“Dogs can run and bark”。利用__init__()构造方法完成Animal和Dog类的对象初始化工作,并编写测试代码。
时间: 2024-02-21 15:02:09 浏览: 67
好的,以下是代码实现:
```python
class Animal:
def __init__(self, color):
self.color = color
def getColor(self):
return self.color
def setColor(self, color):
self.color = color
def abilities(self):
print("Animals can run")
class Dog(Animal):
def __init__(self, color, name):
super().__init__(color)
self.name = name
def getName(self):
return self.name
def setName(self, name):
self.name = name
def abilities(self):
print("Dogs can run and bark")
# 测试代码
animal = Animal("brown")
print("Animal color:", animal.getColor())
animal.setColor("black")
print("Animal color after set:", animal.getColor())
animal.abilities()
dog = Dog("white", "Bobby")
print("Dog color:", dog.getColor())
print("Dog name:", dog.getName())
dog.setName("Max")
print("Dog name after set:", dog.getName())
dog.abilities()
```
输出结果:
```
Animal color: brown
Animal color after set: black
Animals can run
Dog color: white
Dog name: Bobby
Dog name after set: Max
Dogs can run and bark
```
阅读全文