python写代码 利用Python创建一个类Bag,其成员包括实例属性category(种类)和color(颜色),实例方法showInfo()用来输出实例属性category和color的值;创建派生类Backpack,继承Bag类,新增实例属性size(尺寸),重写基类的实例方法showInfo ()输出所有实例属性的值。利用__init__()构造方法完成Bag和Backpack类的对象初始化工作,并编写测试代码。
时间: 2023-05-28 16:02:23 浏览: 74
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("Shoulder bag", "Black")
bag1.showInfo()
backpack1 = Backpack("Backpack", "Red", "Large")
backpack1.showInfo()
```
输出结果为:
```
Category: Shoulder bag
Color: Black
Category: Backpack
Color: Red
Size: Large
```
阅读全文