Py学习  »  Python

如何在向量类中添加不同的向量?python

Quentin • 3 年前 • 1201 次点击  

这是我的第一个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'
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133103
 
1201 次点击  
文章 [ 2 ]  |  最新文章 3 年前