这是我的第一个python程序之一。
我不能用fill_n操作从init创建的向量。我不知道应该更改什么。
另外
“向量的内部表示形式不应在类(受保护字段)之外可见。”
class Vector:
def __init__ (self, lista):
self.value = lista
def __add__ (self, other):
res = Vector( [x + y for x, y in zip(self.value, other.value) ])
return res
def __mul__(self, other):
dot=0
for x, y in zip(self.value, other.value):
dot = dot + x *y
return dot
def fill_n ( size, val):
value=[val]*size
return tuple(value)
def __str__(self):
return ', '.join([str(x) for x in self.value])
def main():
v1 = Vector([1, 2, 3])
v2 = Vector([4, 2, 2])
v3 = Vector.fill_n(3,1)
print (v1 + v2)
print (v1 + v3) #It doesn't work
print(v3)
main()
我得到的错误是:
Traceback (most recent call last):
line 34, in <module>
main()
line 30, in main
print (v1 + v3) #It doesn't work
line 7, in __add__
res = Vector( [x + y for x, y in zip(self.value, other.value) ])
AttributeError: 'tuple' object has no attribute 'value'