设计Student、Course和Teacher类
时间: 2024-05-14 14:12:31 浏览: 111
oracle adb
以下是Python代码实现:
```python
class Student:
def __init__(self, name, id):
self.name = name
self.id = id
self.courses = []
def enroll(self, course):
self.courses.append(course)
def drop(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, teacher):
self.name = name
self.teacher = teacher
self.students = []
def add_student(self, student):
self.students.append(student)
student.enroll(self)
def remove_student(self, student):
self.students.remove(student)
student.drop(self)
def list_students(self):
print(f"Students enrolled in {self.name}:")
for student in self.students:
print(student.name)
class Teacher:
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 list_courses(self):
print(f"{self.name}'s courses:")
for course in self.courses:
print(course.name)
```
使用示例:
```python
# 创建学生、课程和教师实例
alice = Student("Alice", 1)
bob = Student("Bob", 2)
math = Course("Math", Teacher("Mr. Smith", 101))
english = Course("English", Teacher("Mrs. Johnson", 102))
mr_jones = Teacher("Mr. Jones", 103)
# 学生选课
math.add_student(alice)
math.add_student(bob)
english.add_student(alice)
# 教师管理课程
mr_jones.add_course(math)
mr_jones.add_course(english)
# 列出学生和课程信息
alice.list_courses() # Alice's courses: Math, English
bob.list_courses() # Bob's courses: Math
math.list_students() # Students enrolled in Math: Alice, Bob
english.list_students() # Students enrolled in English: Alice
mr_jones.list_courses() # Mr. Jones's courses: Math, English
# 学生退课
math.remove_student(bob)
bob.list_courses() # Bob's courses:
math.list_students() # Students enrolled in Math: Alice
```
阅读全文