用python类写1、输入并存储学生的信息 2、修改学生信息 3、删除学生信息 4、成绩排序 5、查找学生信息 6、进行测试
时间: 2023-10-20 15:10:05 浏览: 83
好的,以下是一个基本的实现:
```python
class Student:
def __init__(self, name, id, grade):
self.name = name
self.id = id
self.grade = grade
class StudentDatabase:
def __init__(self):
self.student_list = []
def add_student(self, name, id, grade):
student = Student(name, id, grade)
self.student_list.append(student)
def modify_student(self, id, new_name, new_grade):
for student in self.student_list:
if student.id == id:
student.name = new_name
student.grade = new_grade
break
def delete_student(self, id):
for student in self.student_list:
if student.id == id:
self.student_list.remove(student)
break
def sort_students(self):
self.student_list.sort(key=lambda x: x.grade, reverse=True)
def find_student(self, id):
for student in self.student_list:
if student.id == id:
return student
def run_tests(self):
self.add_student("Alice", 1, 80)
self.add_student("Bob", 2, 90)
self.add_student("Charlie", 3, 85)
self.modify_student(2, "Bobby", 95)
self.delete_student(3)
self.sort_students()
print("Sorted student list:")
for student in self.student_list:
print(student.name, student.id, student.grade)
print("Finding student with ID 1:")
student = self.find_student(1)
if student:
print(student.name, student.id, student.grade)
else:
print("Student not found.")
```
我们定义了两个类,`Student` 表示学生信息,包括姓名、学号和成绩,`StudentDatabase` 表示学生信息的数据库,包括添加、修改、删除、排序和查找等操作。
我们可以通过 `StudentDatabase` 类的 `run_tests` 方法来测试实现的正确性。
阅读全文