学生选课管理系统python代码
时间: 2023-10-13 18:23:58 浏览: 116
以下是一个简单的学生选课管理系统的Python代码示例,供参考:
```python
class Student:
def __init__(self, name, id):
self.name = name
self.id = id
self.courses = []
def add_course(self, course):
self.courses.append(course)
def remove_course(self, course):
self.courses.remove(course)
def print_courses(self):
print(f"{self.name}'s courses:")
for course in self.courses:
print(course)
class Course:
def __init__(self, name, id):
self.name = name
self.id = id
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 print_students(self):
print(f"{self.name}'s students:")
for student in self.students:
print(student.name)
class CourseCatalog:
def __init__(self):
self.courses = {}
def add_course(self, course):
self.courses[course.id] = course
def remove_course(self, course):
del self.courses[course.id]
def get_course(self, id):
return self.courses.get(id)
def print_courses(self):
print("Course catalog:")
for course in self.courses.values():
print(course.name)
if __name__ == "__main__":
# Example usage
john = Student("John", 1)
jane = Student("Jane", 2)
math = Course("Math", 101)
physics = Course("Physics", 201)
catalog = CourseCatalog()
catalog.add_course(math)
catalog.add_course(physics)
math.add_student(john)
physics.add_student(jane)
john.print_courses()
jane.print_courses()
math.print_students()
physics.print_students()
catalog.print_courses()
```
此代码定义了三个类:`Student`(学生)、`Course`(课程)和`CourseCatalog`(课程目录)。每个学生和课程都有自己的名称和ID,学生可以添加和删除他们的课程,课程可以添加和删除学生。课程目录可以添加和删除课程,并提供了打印所有课程的方法。
在`if __name__ == "__main__":`中的示例使用了这些类,并演示了如何创建学生、课程和课程目录,以及如何将学生添加到课程中,并打印这些信息。
阅读全文