【发布时间】:2017-03-14 16:26:56
【问题描述】:
我已经为 n 维向量定义了一个类:
class Vector:
def __init__(self, v):
if len(v)==0: self.v = (0,0)
else: self.v = v
并且我在类中的一个函数(add)没有返回我想要的值。目前我将其定义为:
for i in range(self.dim()):
newvector.append(self[i+1] + other[i+1])
return Vector
我也试过了:
def __add__(self, other):
for i in range(len(self)):
added = tuple( a + b for a, b in zip(self, other) )
return Vector(*added)
但这会返回 Unsupported Operand Type 错误。
我希望它通过的测试是str(v1 + v2) == 'Vector: [3, 5, 7]',但它正在返回'Vector: [2, 3, 4, 1, 2, 3]'
【问题讨论】:
-
您正在使用运算符
+进行列表连接,而不是添加。 -
除非您为班级定义
__len__和__getitem__,否则您几乎肯定希望使用self.v和other.v,而不是直接使用self和other。
标签: python python-3.x