系统中存在学生和老师两类对象,支持可查询学生姓名、性别和年龄信息且可对学生多门成绩求平均;可查询老师姓名、性别和年龄信息且可对老师所带课程所有学生成绩求平均。编写程序测试这两个类的功能,同时使用类的继承提升代码复用效率
时间: 2024-12-21 08:22:09 浏览: 5
在这个系统中,我们可以创建两个基类`Person`和`Scoreable`,分别代表人(学生和老师)的基本信息,并实现公共的方法。然后,为学生和老师各自创建子类,继承自这两个基类,增加专属字段和方法。接下来,我们编写测试代码来展示功能和复用性。
首先,定义基类:
```python
class Person:
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
def display_info(self):
return f"Name: {self.name}, Gender: {self.gender}, Age: {self.age}"
class Scoreable:
def __init__(self):
self.score_list = []
def add_score(self, score):
self.score_list.append(score)
def average_score(self):
if not self.score_list:
return None
return sum(self.score_list) / len(self.score_list)
# 学生类继承自Person和Scoreable
class Student(Person, Scoreable):
def __init__(self, name, gender, age, scores=None):
super().__init__(name, gender, age)
if scores is not None:
self.add_scores(scores)
# 老师类继承自Person
class Teacher(Person):
def __init__(self, name, gender, age, courses=None):
super().__init__(name, gender, age)
if courses is not None:
for course, student_scores in courses.items():
for student, score in student_scores.items():
self.add_student_score(course, student, score)
def add_student_score(self, course, student, score):
if course not in self.score_list:
self.score_list[course] = {}
self.score_list[course][student] = score
# 测试代码
def test_students():
tom = Student("Tom", "Male", 18, [85, 90, 92])
tom.display_info() # 输出学生信息
avg_score = tom.average_score() # 求平均分
print(f"Average score: {avg_score}")
def test_teachers():
john = Teacher("John", "Male", 35, {"Math": {"Alice": 88, "Bob": 94}})
john.display_info() # 输出老师信息
for course, students_scores in john.score_list.items():
avg_course_score = sum(students_scores.values()) / len(students_scores)
print(f"{course} average score: {avg_course_score}")
test_students()
test_teachers()
```
阅读全文