①设计一个学生类,该类中包含:学号、姓名、python成绩三个属性,分别实现加减乘除的运算符重载,用于引用学生对象名就可以对学生成绩进行加减乘除运算。 ②建立张三、李四两个对象,并利用构造函数传参对其属性信息初始化。③对象的print()方法进行功能改写,提示设置 __str__功能④利用运算符重载,求两人的python成绩的总分和平均分并输出
时间: 2023-12-03 18:46:06 浏览: 26
以下是实现题目要求的代码:
```python
class Student:
def __init__(self, id, name, python_score):
self.id = id
self.name = name
self.python_score = python_score
def __add__(self, other):
return self.python_score + other.python_score
def __sub__(self, other):
return self.python_score - other.python_score
def __mul__(self, other):
return self.python_score * other.python_score
def __truediv__(self, other):
return self.python_score / other.python_score
def __str__(self):
return f"Student: {self.name} (ID: {self.id}), Python score: {self.python_score}"
zhangsan = Student("001", "张三", 80)
lisi = Student("002", "李四", 90)
print(zhangsan)
print(lisi)
total_score = zhangsan + lisi
average_score = total_score / 2
print(f"Total python score: {total_score}")
print(f"Average python score: {average_score}")
```
输出结果如下:
```
Student: 张三 (ID: 001), Python score: 80
Student: 李四 (ID: 002), Python score: 90
Total python score: 170
Average python score: 85.0
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)