编写程序,创建学生成绩中所涉及的类: `Student` 类、 `Teacher` 类、 `Course` 类,并由 `Grade` 类将 `Student` 类、 `Teacher` 类和 `Course` 类关联起来,由 `GradeTest` 类对以上四个类进行测试。
时间: 2023-07-27 17:30:10 浏览: 148
好的,这是一个比较复杂的问题,需要分别实现四个类。以下是我编写的代码,供你参考:
```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)
# 定义教师类
class Teacher:
def __init__(self, name, id):
self.name = name
self.id = id
self.courses = []
def add_course(self, course):
self.courses.append(course)
# 定义课程类
class Course:
def __init__(self, name, id, teacher):
self.name = name
self.id = id
self.teacher = teacher
self.students = []
def add_student(self, student):
self.students.append(student)
# 定义成绩类
class Grade:
def __init__(self, course, student, score):
self.course = course
self.student = student
self.score = score
# 定义测试类
class GradeTest:
def __init__(self):
self.students = []
self.teachers = []
self.courses = []
self.grades = []
def add_student(self, name, id):
self.students.append(Student(name, id))
def add_teacher(self, name, id):
self.teachers.append(Teacher(name, id))
def add_course(self, name, id, teacher_id):
teacher = None
for t in self.teachers:
if t.id == teacher_id:
teacher = t
break
if not teacher:
raise ValueError("Teacher not found")
course = Course(name, id, teacher)
teacher.add_course(course)
self.courses.append(course)
def add_grade(self, course_id, student_id, score):
course = None
for c in self.courses:
if c.id == course_id:
course = c
break
if not course:
raise ValueError("Course not found")
student = None
for s in self.students:
if s.id == student_id:
student = s
break
if not student:
raise ValueError("Student not found")
grade = Grade(course, student, score)
course.add_student(student)
self.grades.append(grade)
def print_grades(self):
for grade in self.grades:
print("{0} {1} {2} {3}".format(grade.course.name, grade.student.name, grade.score, grade.course.teacher.name))
```
这个程序中,`Student` 类、 `Teacher` 类、 `Course` 类分别表示学生、教师和课程,`Grade` 类表示成绩。`Grade` 类将 `Student` 类、 `Teacher` 类和 `Course` 类关联起来,通过 `GradeTest` 类进行测试。`GradeTest` 类中包含了添加学生、教师、课程和成绩的方法,以及打印成绩的方法。你可以根据自己的需求进行修改和扩展。
阅读全文