如何用python实现简单的学生选课系统
时间: 2023-06-19 08:02:52 浏览: 81
以下是一个简单的学生选课系统的 Python 代码示例:
```python
class Student:
def __init__(self, name, id_num):
self.name = name
self.id_num = id_num
self.courses = []
def add_course(self, course):
self.courses.append(course)
def remove_course(self, course):
self.courses.remove(course)
class Course:
def __init__(self, name, id_num, professor):
self.name = name
self.id_num = id_num
self.professor = professor
self.students = []
def add_student(self, student):
self.students.append(student)
student.add_course(self)
def remove_student(self, student):
self.students.remove(student)
student.remove_course(self)
def list_students(self):
for student in self.students:
print(student.name)
class School:
def __init__(self):
self.students = []
self.courses = []
def add_student(self, name, id_num):
student = Student(name, id_num)
self.students.append(student)
def add_course(self, name, id_num, professor):
course = Course(name, id_num, professor)
self.courses.append(course)
def register_student(self, student_id, course_id):
student = self.get_student_by_id(student_id)
course = self.get_course_by_id(course_id)
course.add_student(student)
def unregister_student(self, student_id, course_id):
student = self.get_student_by_id(student_id)
course = self.get_course_by_id(course_id)
course.remove_student(student)
def list_students_in_course(self, course_id):
course = self.get_course_by_id(course_id)
course.list_students()
def get_student_by_id(self, student_id):
for student in self.students:
if student.id_num == student_id:
return student
return None
def get_course_by_id(self, course_id):
for course in self.courses:
if course.id_num == course_id:
return course
return None
# Example usage
school = School()
school.add_student("Alice", 1234)
school.add_student("Bob", 5678)
school.add_course("Math", 1001, "Prof. Smith")
school.add_course("Science", 1002, "Prof. Johnson")
school.register_student(1234, 1001)
school.register_student(5678, 1001)
school.register_student(5678, 1002)
school.list_students_in_course(1001)
```
这个简单的学生选课系统包括三个类:`Student`,`Course`和`School`。`Student`类表示学生,`Course`类表示课程,`School`类表示学校。在`School`类中,有一些方法可以添加学生和课程,注册学生到课程中,取消学生在课程中的注册,列出某个课程中的所有学生等。
阅读全文