编写程序,创建基类Animal,其成员包括实例属性color,实例方法getColor()和setColor()分别用来获取和设置color的值,实例方法 abilities()输出字符串“Animals can run”。创建派生类Dog,继承Animal类,新增实例属性name,新增实例方法getName()和setName()分别用来获取和设置name的值,重写基类的实例方法 abilities(),输出字符串“Dogs can run and bark”。利用__init__()构造方法完成Animal和Dog类的对象初始化工作,并编写测试代码python编写完整代码和步骤
时间: 2024-02-21 07:02:12 浏览: 68
C抽象基类和纯虚成员函数-C教程共3页.pdf.zip
步骤如下:
1. 定义基类Animal,包括实例属性color,实例方法getColor()和setColor(),实例方法abilities()。
```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")
```
2. 定义派生类Dog,继承Animal类,新增实例属性name,新增实例方法getName()和setName(),重写基类的实例方法abilities()。
```python
class Dog(Animal):
def __init__(self, name, color):
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")
```
3. 编写测试代码,分别创建Animal和Dog类的对象,并调用各自的方法进行测试。
```python
# 创建Animal对象并测试
animal = Animal("brown")
print("Animal color:", animal.getColor())
animal.setColor("white")
print("Animal color after setting:", animal.getColor())
animal.abilities()
# 创建Dog对象并测试
dog = Dog("Buddy", "black")
print("Dog name:", dog.getName())
print("Dog color:", dog.getColor())
dog.setName("Charlie")
print("Dog name after setting:", dog.getName())
dog.abilities()
```
完整代码如下:
```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, name, color):
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 = Animal("brown")
print("Animal color:", animal.getColor())
animal.setColor("white")
print("Animal color after setting:", animal.getColor())
animal.abilities()
# 创建Dog对象并测试
dog = Dog("Buddy", "black")
print("Dog name:", dog.getName())
print("Dog color:", dog.getColor())
dog.setName("Charlie")
print("Dog name after setting:", dog.getName())
dog.abilities()
```
阅读全文