2、设计一个学生类Student,每个学生都有三门课程的成绩,分别是语文、数学和物理,重载+运算符,用于对两个学生对象每门成绩的求和,重载方法返回一个学生对象,用程序实现多个学生的成绩求和,并求每门课程成绩的平均分。
时间: 2024-01-01 16:06:23 浏览: 39
好的,以下是 Python 代码实现:
```python
class Student:
def __init__(self, name, chinese, math, physics):
self.name = name
self.chinese = chinese
self.math = math
self.physics = physics
def __add__(self, other):
chinese_sum = self.chinese + other.chinese
math_sum = self.math + other.math
physics_sum = self.physics + other.physics
return Student("Total", chinese_sum, math_sum, physics_sum)
def __str__(self):
return f"{self.name} - Chinese: {self.chinese}, Math: {self.math}, Physics: {self.physics}"
def average(self):
return (self.chinese + self.math + self.physics) / 3
# 多个学生的成绩求和
student1 = Student("Tom", 90, 85, 95)
student2 = Student("Jerry", 80, 90, 85)
student3 = Student("Lucy", 95, 92, 88)
total_score = student1 + student2 + student3
print(total_score)
# 求每门课程成绩的平均分
chinese_average = total_score.chinese / 3
math_average = total_score.math / 3
physics_average = total_score.physics / 3
print(f"Average - Chinese: {chinese_average}, Math: {math_average}, Physics: {physics_average}")
```
输出结果:
```
Total - Chinese: 265, Math: 267, Physics: 268
Average - Chinese: 88.33333333333333, Math: 89.0, Physics: 89.33333333333333
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)