利用Python创建一个类Bag,其成员包括实例属性category(种类)和color(颜色),实例方法showInfo()用来输出实例属性category和color的值;创建派生类Backpack,继承Bag类,新增实例属性size(尺寸),重写基类的实例方法showInfo ()输出所有实例属性的值。利用__init__()构造方法完成Bag和Backpack类的对象初始化工作,并编写测试代码。
时间: 2023-05-26 08:05:08 浏览: 45
```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
```
相关问题
创建一个抽象父类 Animal,具有属性Name 和 Age ,并有一个抽象方法showInfo().
```python
from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self, name, age):
self.name = name
self.age = age
@abstractmethod
def showInfo(self):
pass
```
解释:
1. 导入 ABC 和 abstractmethod 来定义抽象类和抽象方法。
2. 创建 Animal 类,继承 ABC 抽象类。
3. 定义构造方法,初始化两个属性 Name 和 Age。
4. 使用 @abstractmethod 装饰器定义抽象方法 showInfo(),在子类中必须实现该方法。
Python编写代码,定义一个Person类,该类包含实例属性name(姓名),gender(性别)和age(年龄),还包含实例方法showInfo(),用于输出3个实例属性;以 Person类为基础定义一个Student类,新增3个实例属性,即sid(学号)、chn(语文)和math(数学),并对实例方法showInfo()进行重写,用于输出6个实例属性。
好的,以下是Python代码实现:
```python
# 定义 Person 类
class Person:
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
def showInfo(self):
print("姓名:{}\n性别:{}\n年龄:{}".format(self.name, self.gender, self.age))
# 定义 Student 类,继承自 Person 类
class Student(Person):
def __init__(self, name, gender, age, sid, chn, math):
super().__init__(name, gender, age)
self.sid = sid
self.chn = chn
self.math = math
def showInfo(self):
print("姓名:{}\n性别:{}\n年龄:{}\n学号:{}\n语文:{}\n数学:{}"
.format(self.name, self.gender, self.age, self.sid, self.chn, self.math))
# 测试代码
p1 = Person("张三", "男", 18)
p1.showInfo()
s1 = Student("李四", "女", 20, "20210001", 90, 85)
s1.showInfo()
```
输出结果:
```
姓名:张三
性别:男
年龄:18
姓名:李四
性别:女
年龄:20
学号:20210001
语文:90
数学:85
```