用Python写一个学生选课管理系统的代码
时间: 2023-06-05 15:06:18 浏览: 435
好的,我可以帮您解决这个问题。以下是一个简单的Python学生选课管理系统的示例代码:
```python
class Course:
def __init__(self, name, max_students):
self.name = name
self.max_students = max_students
self.students = []
def add_student(self, student):
if len(self.students) < self.max_students:
self.students.append(student)
print("Student '{}' added to course '{}'".format(student.name, self.name))
return True
else:
print("Sorry, course '{}' is full. Cannot add student '{}'".format(self.name, student.name))
return False
class Student:
def __init__(self, name):
self.name = name
self.courses = []
def enroll(self, course):
if course.add_student(self):
self.courses.append(course)
print("Student '{}' enrolled in course '{}'".format(self.name, course.name))
def show_courses(self):
if len(self.courses) > 0:
print("Courses enrolled in by student '{}':".format(self.name))
for course in self.courses:
print("- {}".format(course.name))
else:
print("Student '{}' is not enrolled in any courses.".format(self.name))
c1 = Course("Math", 2)
c2 = Course("Science", 1)
c3 = Course("History", 3)
s1 = Student("Alice")
s2 = Student("Bob")
s1.enroll(c1)
s2.enroll(c1)
s1.show_courses()
s2.show_courses()
s2.enroll(c2)
s2.show_courses()
s1.enroll(c3)
s2.enroll(c3)
s1.show_courses()
s2.show_courses()
```
这个示例代码定义了两个类,即Course(课程)和Student(学生)。Course类包含一些基本属性,如课程名称和最大学生数量,以及用于添加学生到课程中的方法。Student类也包含基本属性,如学生姓名和所选课程列表,以及用于将学生添加到课程中的方法。在示例代码的最后,我们创建了几个课程和学生实例,并使用它们添加和显示课程选修情况。
希望这个示例代码能帮助您!
阅读全文