创建一个Teacher类 ü是People的子类,新增属性school ümoveto方法改为newschool ü按照school排序 ü创建4个教师对象,放到列表进行排序
时间: 2024-12-13 14:24:01 浏览: 4
创建一个名为`Teacher`的类,它是`People`类的子类,我们会在其中添加一个新的属性`school`。同时,我们将更新`moveTo`方法为`newSchool`,使其接受新的学校信息。为了能够按照`school`属性进行排序,我们可以重写`__lt__`方法,让Python的内置排序函数能工作。以下是这个类的实现:
```python
class People:
def __init__(self):
pass
class Teacher(People):
def __init__(self, name, age, school):
super().__init__()
self.name = name
self.age = age
self.school = school
def newSchool(self, new_school):
self.school = new_school
def __lt__(self, other):
return self.school < other.school
# 创建四个教师对象,并设置各自的学校
teacher1 = Teacher("张三", 30, "A校")
teacher2 = Teacher("李四", 25, "B校")
teacher3 = Teacher("王五", 35, "C校")
teacher4 = Teacher("赵六", 28, "D校")
# 将教师对象放入列表并按school排序
teachers = [teacher1, teacher2, teacher3, teacher4]
sorted_teachers = sorted(teachers)
# 打印排序后的教师列表
for teacher in sorted_teachers:
print(f"{teacher.name} from {teacher.school}")
阅读全文