利用Python创建一个类Bag,其成员包括实例属性category(种类)和color(颜色),实例方法showInfo()用来输出实例属性category和color的值;创建派生类Backpack,继承Bag类,新增实例属性size(尺寸),重写基类的实例方法showInfo ()输出所有实例属性的值。利用__init__()构造方法完成Bag和Backpack类的对象初始化工作,并编写测试代码。
时间: 2023-05-26 15:05:08 浏览: 127
Python编程之属性和方法实例详解
```python
class Bag:
def __init__(self, category, color):
self.category = category
self.color = color
def showInfo(self):
print("Category: ", self.category)
print("Color: ", self.color)
class Backpack(Bag):
def __init__(self, category, color, size):
super().__init__(category, color)
self.size = size
def showInfo(self):
super().showInfo()
print("Size: ", self.size)
# 测试代码
bag1 = Bag("tote", "black")
bag1.showInfo()
print("")
backpack1 = Backpack("hiking", "green", "medium")
backpack1.showInfo()
```
输出:
```
Category: tote
Color: black
Category: hiking
Color: green
Size: medium
```
阅读全文