创建一个类Teacher 是People的子类,新增属性school moveto方法中的参数改为newschool 按照school排序 创建4个教师对象,放到列表进行排序、
时间: 2024-01-26 17:05:14 浏览: 104
好的,以下是实现代码:
```python
class People:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
class Teacher(People):
def __init__(self, name, age, gender, school):
super().__init__(name, age, gender)
self.school = school
def moveto(self, newschool):
self.school = newschool
teachers = [
Teacher("Alice", 35, "Female", "A School"),
Teacher("Bob", 40, "Male", "B School"),
Teacher("Cathy", 30, "Female", "C School"),
Teacher("David", 45, "Male", "D School")
]
sorted_teachers = sorted(teachers, key=lambda x: x.school)
for teacher in sorted_teachers:
print("{} ({}, {}) - {}".format(teacher.name, teacher.age, teacher.gender, teacher.school))
```
输出结果:
```
Alice (35, Female) - A School
Bob (40, Male) - B School
Cathy (30, Female) - C School
David (45, Male) - D School
```
这里定义了一个 `Teacher` 类,它继承自 `People` 类,并新增了一个属性 `school`,表示该老师所在的学校。同时,`moveto` 方法的参数也改成了 `newschool`,用于修改 `school` 属性的值。
接着,我们创建了四个 `Teacher` 对象,并将它们存放在列表 `teachers` 中。使用 `sorted` 函数对 `teachers` 列表进行排序,按照 `school` 属性从小到大的顺序排列。最后,遍历排序后的列表并输出每个老师的信息。
阅读全文