Python实现学生管理系统的示例代码

  class Student:

  def __init__(self, student_id, name, age, gender):

  self.student_id = student_id

  self.name = name

  self.age = age

  self.gender = gender

  def display_info(self):

  print(f"学号:{self.student_id}")

  print(f"姓名:{self.name}")

  print(f"年龄:{self.age}")

  print(f"性别:{self.gender}")

  class StudentManagementSystem:

  def __init__(self):

  self.students = []

  def add_student(self, student):

  self.students.append(student)

  def remove_student(self, student_id):

  for student in self.students:

  if student.student_id == student_id:

  self.students.remove(student)

  print("删除成功!")

  return

  print("未找到学号对应的学生!")

  def modify_student_info(self, student_id, name, age, gender):

  for student in self.students:

  if student.student_id == student_id:

  student.name = name

  student.age = age

  student.gender = gender

  print("修改成功!")

  return

  print("未找到学号对应的学生!")

  def search_student_info(self, keyword):

  for student in self.students:

  if keyword in (student.student_id, student.name):

  student.display_info()

  def display_all_students(self):

  if len(self.students) == 0:

  print("系统中暂无学生信息!")

  else:

  for student in self.students:

  student.display_info()

  def save_students_info(self, filename):

  with open(filename, "w") as file:

  for student in self.students:

  file.write(f"{student.student_id},{student.name},{student.age},{student.gender}

  ")

  print("学生信息保存成功!")

  def load_students_info(self, filename):

  self.students = []

  try:

  with open(filename, "r") as file:

  lines = file.readlines()

  for line in lines:

  student_data = line.strip().split(",")

  student = Student(student_data[0], student_data[1], int(student_data[2]), student_data[3])

  self.students.append(student)

  print("学生信息加载成功!")

  except FileNotFoundError:

  print("找不到指定的学生信息文件!")