改进以下代码class Student: def __init__(self, num, name, scores): self.num=num self.name=name self.scores=scores def __getitem__(self, index): return self.scores[index] def __setitem__(self, index, value): self.scores[index]=value def __delitem__(self, index): del self.scores[index] def __str__(self): return self.name+"成绩为:"+self.scores zhangsan=Student("100001", "张三", [91, 87, 81.5, 69, 97, 88, 69, 78.5]) lisi=Student("100002", "李四", [95, 91, 88, 87, 97.5, 69.5, 92, 78.5]) zhangsan[0] = 102 del lisi[5:] print(zhangsan) print(lisi)
时间: 2024-01-27 09:02:43 浏览: 107
你可以尝试这样改进代码:
```
class Student:
def __init__(self, num, name, scores):
self.num = num
self.name = name
self.scores = scores
def __getitem__(self, index):
return self.scores[index]
def __setitem__(self, index, value):
self.scores[index] = value
def __delitem__(self, index):
if isinstance(index, slice):
del self.scores[index]
else:
del self.scores[index]
def __str__(self):
return f"{self.name}的成绩为:{', '.join(str(score) for score in self.scores)}"
zhangsan = Student("100001", "张三", [91, 87, 81.5, 69, 97, 88, 69, 78.5])
lisi = Student("100002", "李四", [95, 91, 88, 87, 97.5, 69.5, 92, 78.5])
zhangsan[0] = 102
del lisi[5:]
print(zhangsan)
print(lisi)
```
主要改进:
1. 在 `__delitem__` 方法中增加对 `slice` 对象的处理,以支持删除多个元素。
2. 在 `__str__` 方法中使用 `join` 拼接字符串,以更好地展示学生成绩。
3. 使用 f-string 格式化字符串,使代码更简洁易读。
阅读全文