Files
AI0814_jiaoan_public/w0_d6/04_students_class_crud.py
2026-09-21 17:11:35 +08:00

131 lines
3.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
04 类版本:学生增删改查
相比函数版本:
1. Student 表示一个学生。
2. StudentManager 表示学生管理器。
3. 数据和操作数据的方法被组织到类里面。
"""
class Student:
def __init__(self, student_id, name, age, phone):
self.id = student_id
self.name = name
self.age = age
self.phone = phone
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"age": self.age,
"phone": self.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()
student = Student(self.next_id, name, age, phone)
self.students.append(student)
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()
found = False
for student in self.students:
if student.name == keyword:
print(student)
found = True
if not found:
print("没有找到该学生")
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("删除成功")
def show_menu(self):
print("\n====== 学生管理系统:类版本 ======")
print("1. 添加学生")
print("2. 查看所有学生")
print("3. 查询学生")
print("4. 修改学生")
print("5. 删除学生")
print("0. 退出")
def run(self):
while True:
self.show_menu()
choice = input("请输入操作编号:").strip()
if choice == "1":
self.add_student()
elif choice == "2":
self.list_students()
elif choice == "3":
self.search_student()
elif choice == "4":
self.update_student()
elif choice == "5":
self.delete_student()
elif choice == "0":
print("程序结束")
break
else:
print("输入有误,请重新输入")
if __name__ == "__main__":
manager = StudentManager()
manager.run()