使用Python向量重载加法

时间:2013-12-11 01:27:56

标签: python class

正如你所看到的,我创建了一个允许我创建和改变矢量的函数。现在我正在尝试使用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)

1 个答案:

答案 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