在我尝试定义一个n维Vector类时,我在定义乘法时遇到了'语法'错误,我真的不知道如何绕过......
class Vector:
def __init__(self, v):
if len(v)==0: self.v = (0,0)
else: self.v = v
#bunch of functions in between here....
def __mul__(self, other):
if type(other) == Vector:
if len(self.v) != len(other.v):
raise AssertionError
dotprod = 0
for i in range(len(self.v)):
dotprod += self.v[i+1] * other.v[i+1]
return dotprod
elif type(other) in [int, float]:
new = []
for component in self.v:
new.append(component*other)
return Vector(tuple(new))
else:
raise AssertionError
错误如下:
File "<ipython-input-52-50a37fd0919a>", line 40
elif type(other) in [int, float]:
^
SyntaxError: invalid syntax
我多次使用缩进和elif语句,我真的看不出是什么问题。
提前致谢。
答案 0 :(得分:3)
问题肯定是缩进错误。我认为这就是你的意图:
def __mul__(self, other):
if type(other) == Vector:
if len(self.v) != len(other.v):
raise AssertionError
dotprod = 0
for i in range(len(self.v)):
dotprod += self.v[i+1] * other.v[i+1]
return dotprod
elif type(other) in [int, float]:
new = []
for component in self.v:
new.append(component*other)
return Vector(tuple(new))
else:
raise AssertionError
这会使elif
与if
处于同一缩进级别。