3-5编写一个学生 类student,包含的属性有学号、姓名、性别、年龄等,将所有学生存储在一个数组中,编写学生管理程序实现如下操作: (1)增加一个学生; (2)根据学号删除某个学生; (3)将所有学生年龄增加一岁; (4)按数组中顺序显示所有学生信息; (5)将所有学生按姓名排序输出。
时间: 2023-05-28 20:07:06 浏览: 120
学生信息管理系统,实现学生信息包括:学号、姓名、性别、年龄、班级等信息。
5星 · 资源好评率100%
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 delete_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 display_all_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)
# 测试代码
manager = StudentManager()
# 添加学生
s1 = Student("001", "张三", "男", 18)
s2 = Student("002", "李四", "女", 19)
s3 = Student("003", "王五", "男", 20)
manager.add_student(s1)
manager.add_student(s2)
manager.add_student(s3)
# 显示所有学生信息
manager.display_all_students()
# 根据学号删除学生
manager.delete_student("002")
manager.display_all_students()
# 年龄增加一岁
manager.increase_age()
manager.display_all_students()
# 按姓名排序输出
manager.sort_students_by_name()
manager.display_all_students()
阅读全文