正如你所看到的,我创建了一个允许我创建和改变矢量的函数。现在我正在尝试使用def __add__(self, y)
将向量添加到一起。但是,我得到了IndexError
。有什么明显的东西你可以看到我的代码出错了,因为我遇到了问题。
def __add__(self, y):
self.vector = []
for j in range(len(self.vector)):
self.vector.append(self.vector[j] + y.self.vector[j])
return Vec(self.vector)
答案 0 :(得分:1)
您的代码中存在一些问题:
self.vector = []
时,您基本上清除了矢量。这使得无法将其添加到另一个向量中。return Vec(self.vector)
时,您将列表传递给Vec
构造函数 - 但您已将其定义为采用向量长度。以下是__add__
可能实现的问题:
def __add__(self, y):
size = len(self.vector)
if size != len(y.vector):
raise ValueError("Vectors must be the same size.")
result = Vec(size)
for j in range(size):
result.vector[j] = self.vector[j] + y.vector[j]
return result