请根据样例程序代码,定义Student类,实现两个学生对象从小到大输出。
时间: 2024-02-13 20:02:15 浏览: 23
好的,以下是定义Student类并实现从小到大排序的代码:
```python
class Student:
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def __lt__(self, other):
if self.score != other.score:
return self.score < other.score
elif self.name != other.name:
return self.name < other.name
else:
return self.age < other.age
def __str__(self):
return f"{self.name} {self.age} {self.score}"
students = [Student("Tom", 20, 90), Student("Bob", 18, 70), Student("Lily", 22, 80)]
students.sort()
for student in students:
print(student)
```
在上面的代码中,我们定义了一个`Student`类,包含三个属性:姓名、年龄和分数。我们通过实现`__lt__`方法来指定排序规则,先按照分数从小到大排序,如果分数相同,则按照姓名的字典序排序,如果姓名也相同,则按照年龄从小到大排序。最后我们创建了三个学生对象,并将它们存储在列表中,然后使用`sort`方法进行排序,最后按照从小到大的顺序输出所有学生的信息。