2.(学号尾号为1340同)编写一个Family类,里面有三个家庭成员(father motherchild类对象)、寝室号等属性,以及寝室挑选某同学打扫卫生的动作。编写一个people类,包含:姓名、年龄、审稿等属性,以及吃饭、睡觉等动作。 在第三个Test 类中,创建1个家庭和3名同学,要求有你本人,本人姓名和学号必须是真实的。并让3个人在选出 1个人打扫卫生(推荐使用多态)。
时间: 2024-03-14 07:46:30 浏览: 75
好的,我来帮您编写这个程序。
首先,我们需要先定义三个类:Father、Mother、Child,它们都继承自People类。代码如下:
```python
class People:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(f"{self.name} is eating...")
def sleep(self):
print(f"{self.name} is sleeping...")
class Father(People):
def __init__(self, name, age):
super().__init__(name, age)
class Mother(People):
def __init__(self, name, age):
super().__init__(name, age)
class Child(People):
def __init__(self, name, age):
super().__init__(name, age)
```
接着,我们定义一个Family类,它包含三个家庭成员和寝室号等属性,以及挑选某个同学打扫卫生的动作。代码如下:
```python
class Family:
def __init__(self, father, mother, child, dormitory):
self.father = father
self.mother = mother
self.child = child
self.dormitory = dormitory
def clean(self, people):
print(f"{people.name} is cleaning the dormitory...")
def select_cleaner(self):
cleaners = [self.father, self.mother, self.child]
import random
cleaner = random.choice(cleaners)
return cleaner
```
最后,我们定义一个Test类,创建一个家庭和三名同学,让这三个人中选出一个人来打扫卫生。代码如下:
```python
class Test:
def run(self):
father = Father("张三", 40)
mother = Mother("李四", 38)
child = Child("王五", 10)
family = Family(father, mother, child, "A101")
student1 = People("学生1", 20)
student2 = People("学生2", 21)
student3 = People("学生3", 22)
cleaner = family.select_cleaner()
family.clean(cleaner)
```
运行Test类的run方法,程序就可以自动选择一个人来打扫卫生了。
阅读全文