基于学生类的选课系统源代码
时间: 2023-07-26 16:38:42 浏览: 87
以下是一个基于学生类的选课系统的示例代码:
```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 drop_course(self, course):
self.courses.remove(course)
def list_courses(self):
print(f"Student {self.name} ({self.id}) is enrolled in the following courses:")
for course in self.courses:
print(f"- {course}")
class Course:
def __init__(self, name, code):
self.name = name
self.code = code
self.students = []
def add_student(self, student):
self.students.append(student)
student.add_course(self)
def drop_student(self, student):
self.students.remove(student)
student.drop_course(self)
def list_students(self):
print(f"The following students are enrolled in course {self.name} ({self.code}):")
for student in self.students:
print(f"- {student.name} ({student.id})")
# Example usage
if __name__ == "__main__":
s1 = Student("Alice", 123)
s2 = Student("Bob", 456)
c1 = Course("Math", "MATH101")
c2 = Course("Science", "SCI202")
c1.add_student(s1)
c1.add_student(s2)
c2.add_student(s2)
s1.list_courses()
s2.list_courses()
c1.list_students()
c2.list_students()
c1.drop_student(s2)
s2.list_courses()
c1.list_students()
```
在这个示例代码中,我们定义了两个类:学生和课程。每个学生可以选择多个课程,每个课程可以有多个学生。在学生类中,我们定义了添加课程、删除课程和列出所选课程的方法。在课程类中,我们定义了添加学生、删除学生和列出所选学生的方法。在示例代码的最后,我们演示了如何使用这些类来实现一个简单的选课系统。
阅读全文