用python写学生选课管理系统的代码
时间: 2023-09-26 21:15:10 浏览: 94
基于Python实现的学生选课管理系统源码+数据库文件.zip
5星 · 资源好评率100%
好的,下面是一个简单的学生选课管理系统的 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 drop_course(self, course):
self.courses.remove(course)
def list_courses(self):
print(f"{self.name}'s courses:")
for course in self.courses:
print(course.name)
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 drop_student(self, student):
self.students.remove(student)
student.drop_course(self)
def list_students(self):
print(f"{self.name}'s students:")
for student in self.students:
print(student.name)
class EnrollmentSystem:
def __init__(self):
self.students = []
self.courses = []
def add_student(self, name, id):
student = Student(name, id)
self.students.append(student)
return student
def add_course(self, name, id):
course = Course(name, id)
self.courses.append(course)
return course
def enroll(self, student, course):
course.add_student(student)
def drop(self, student, course):
course.drop_student(student)
def list_students(self):
print("All students:")
for student in self.students:
print(student.name)
def list_courses(self):
print("All courses:")
for course in self.courses:
print(course.name)
# Example usage
enrollment_system = EnrollmentSystem()
# Add students
alice = enrollment_system.add_student("Alice", 1)
bob = enrollment_system.add_student("Bob", 2)
charlie = enrollment_system.add_student("Charlie", 3)
# Add courses
math = enrollment_system.add_course("Math", 101)
physics = enrollment_system.add_course("Physics", 102)
chemistry = enrollment_system.add_course("Chemistry", 103)
# Enroll students in courses
enrollment_system.enroll(alice, math)
enrollment_system.enroll(alice, physics)
enrollment_system.enroll(bob, chemistry)
enrollment_system.enroll(charlie, math)
enrollment_system.enroll(charlie, chemistry)
# List students and courses
enrollment_system.list_students()
enrollment_system.list_courses()
# List courses for each student
alice.list_courses()
bob.list_courses()
charlie.list_courses()
# List students for each course
math.list_students()
physics.list_students()
chemistry.list_students()
# Drop a course for a student
enrollment_system.drop(alice, math)
alice.list_courses()
math.list_students()
```
这个系统包含了三个类:学生、课程和选课系统,以及它们之间的关系和交互方法。通过创建实例并调用这些方法,可以进行学生选课和管理。
阅读全文