用python编写一个简单的学生管理系统
时间: 2023-08-02 19:09:42 浏览: 81
Python编写简单的学生管理系统
好的,下面是一个简单的学生管理系统的 Python 代码:
```python
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
class StudentManagementSystem:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def remove_student(self, student):
self.students.remove(student)
def get_student_by_name(self, name):
for student in self.students:
if student.name == name:
return student
return None
def get_student_by_age(self, age):
result = []
for student in self.students:
if student.age == age:
result.append(student)
return result
def get_student_by_grade(self, grade):
result = []
for student in self.students:
if student.grade == grade:
result.append(student)
return result
# 测试代码
s1 = Student('Tom', 18, 10)
s2 = Student('Jerry', 17, 9)
s3 = Student('Alice', 19, 11)
sms = StudentManagementSystem()
sms.add_student(s1)
sms.add_student(s2)
sms.add_student(s3)
print(sms.get_student_by_name('Tom').age) # 输出:18
print(len(sms.get_student_by_age(18))) # 输出:1
print(len(sms.get_student_by_grade(10))) # 输出:1
sms.remove_student(s2)
print(len(sms.students)) # 输出:2
```
这段代码定义了两个类,`Student` 和 `StudentManagementSystem`。`Student` 类表示一个学生,包含了学生的姓名、年龄和年级。`StudentManagementSystem` 类表示一个学生管理系统,包含了添加、删除和查询学生的功能。在测试代码中,我们创建了三个学生,并添加到学生管理系统中,然后测试了各种查询功能。
阅读全文