5.设计一个学生类Student,每个学生都有三门课程的成绩,分别是语文、数学和物理。重载“+”运算符,用于两个学生对象每门成绩的求和,重载方法返回一个学生对象。用程序实现多个学生的成绩求和,并求每门课程成绩的平均分。使用python
时间: 2024-10-21 17:15:59 浏览: 24
首先,我们定义一个名为`Student`的类,包含姓名和三个成绩属性(语文、数学、物理),以及重载的"+"运算符和一个计算平均成绩的方法。
```python
class Student:
def __init__(self, name, chinese_score, math_score, physics_score):
self.name = name
self.chinese_score = chinese_score
self.math_score = math_score
self.physics_score = physics_score
def __add__(self, other): # 重载加法运算符
if not isinstance(other, Student):
raise ValueError("Can only add another student object")
return Student(self.name, self.chinese_score + other.chinese_score,
self.math_score + other.math_score, self.physics_score + other.physics_score)
@staticmethod
def average_scores(students_list, subject):
total_score = sum([student.__getattribute__(subject) for student in students_list])
num_students = len(students_list)
return total_score / num_students if num_students > 0 else None
# 示例:创建几个学生对象
student1 = Student('Alice', 85, 90, 92)
student2 = Student('Bob', 90, 87, 95)
student3 = Student('Charlie', 88, 92, 89)
# 将学生对象相加
total_student = student1 + student2 + student3
# 求每门课程的平均分
avg_chinese = Student.average_scores([student1, student2, student3], 'chinese_score')
avg_math = Student.average_scores([student1, student2, student3], 'math_score')
avg_physics = Student.average_scores([student1, student2, student3], 'physics_score')
print(f"Total student: {total_student}")
print(f"Average scores:\nChinese: {avg_chinese}\nMath: {avg_math}\nPhysics: {avg_physics}")
```
在这个程序中,我们定义了`Student`类,其中包含`__add__`方法用于两个学生对象成绩的累加。`average_scores`是一个静态方法,用于计算列表中所有学生某一科目成绩的平均值。
当我们创建多个学生对象并将它们相加时,它将返回一个新的学生对象,表示他们各自成绩的总和。然后我们可以调用`average_scores`方法来计算各科目的平均成绩。
阅读全文