""" 05 类 + 反射版本:学生增删改查 反射的核心: 根据字符串找到对象上的方法。 普通写法: if choice == "1": manager.add_student() 反射写法: method_name = menu[choice] method = getattr(manager, method_name) method() 这样做的好处: 菜单编号和方法名可以放到一个字典里统一管理。 """ class Student: def __init__(self, student_id, name, age, phone): self.id = student_id self.name = name self.age = age self.phone = phone def __str__(self): return f"ID: {self.id}, 姓名: {self.name}, 年龄: {self.age}, 电话: {self.phone}" class StudentManager: def __init__(self): self.students = [] self.next_id = 1 def add_student(self): name = input("姓名:").strip() age = input("年龄:").strip() phone = input("电话:").strip() self.students.append(Student(self.next_id, name, age, phone)) self.next_id += 1 print("添加成功") def list_students(self): if not self.students: print("暂无学生") return for student in self.students: print(student) def find_student_by_id(self, student_id): for student in self.students: if str(student.id) == str(student_id): return student return None def search_student(self): keyword = input("请输入要查询的姓名:").strip() result = [student for student in self.students if student.name == keyword] if not result: print("没有找到该学生") return for student in result: print(student) def update_student(self): student_id = input("请输入要修改的学生 ID:").strip() student = self.find_student_by_id(student_id) if student is None: print("没有找到该学生") return student.name = input("新姓名:").strip() student.age = input("新年龄:").strip() student.phone = input("新电话:").strip() print("修改成功") def delete_student(self): student_id = input("请输入要删除的学生 ID:").strip() student = self.find_student_by_id(student_id) if student is None: print("没有找到该学生") return self.students.remove(student) print("删除成功") class Application: def __init__(self): self.manager = StudentManager() self.menu = { "1": ("添加学生", "add_student"), "2": ("查看所有学生", "list_students"), "3": ("查询学生", "search_student"), "4": ("修改学生", "update_student"), "5": ("删除学生", "delete_student"), } def show_menu(self): print("\n====== 学生管理系统:类 + 反射版本 ======") for key, value in self.menu.items(): title, _ = value print(f"{key}. {title}") print("0. 退出") def run(self): while True: self.show_menu() choice = input("请输入操作编号:").strip() if choice == "0": print("程序结束") break if choice not in self.menu: print("输入有误,请重新输入") continue _, method_name = self.menu[choice] method = getattr(self.manager, method_name) method() if __name__ == "__main__": app = Application() app.run()