3-5 编写一个学生类student,包含的属性有学号、姓名、性别、年龄等,将所有学生存储 在一个数组中,编写学生管理程序实现如下操作: (1)增加一个学生; (2)根据学号删除某个学生; (3)将所有学生年龄增加一岁; (4)按数组中顺序显示所有学生信息; (5)将所有学牛按姓名排序输出。
时间: 2023-05-30 11:02:10 浏览: 93
```python
class Student:
def __init__(self, id, name, gender, age):
self.id = id
self.name = name
self.gender = gender
self.age = age
class StudentManager:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def remove_student(self, id):
for student in self.students:
if student.id == id:
self.students.remove(student)
break
def increase_age(self):
for student in self.students:
student.age += 1
def show_students(self):
for student in self.students:
print("学号:{},姓名:{},性别:{},年龄:{}".format(student.id, student.name, student.gender, student.age))
def sort_students_by_name(self):
self.students.sort(key=lambda x: x.name)
# 测试代码
if __name__ == "__main__":
manager = StudentManager()
# 增加学生
manager.add_student(Student("001", "张三", "男", 18))
manager.add_student(Student("002", "李四", "女", 17))
manager.add_student(Student("003", "王五", "男", 19))
# 显示学生信息
manager.show_students()
# 删除学生
manager.remove_student("002")
# 显示学生信息
manager.show_students()
# 增加学生年龄
manager.increase_age()
# 显示学生信息
manager.show_students()
# 按姓名排序
manager.sort_students_by_name()
# 显示学生信息
manager.show_students()
```
输出结果:
```
学号:001,姓名:张三,性别:男,年龄:18
学号:002,姓名:李四,性别:女,年龄:17
学号:003,姓名:王五,性别:男,年龄:19
学号:001,姓名:张三,性别:男,年龄:18
学号:003,姓名:王五,性别:男,年龄:19
学号:001,姓名:张三,性别:男,年龄:19
学号:003,姓名:王五,性别:男,年龄:20
学号:001,姓名:张三,性别:男,年龄:20
学号:003,姓名:王五,性别:男,年龄:21
学号:003,姓名:王五,性别:男,年龄:21
学号:001,姓名:张三,性别:男,年龄:20
```
阅读全文