Py学习  »  Python

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

Quentin • 3 年前 • 1199 次点击  

这是我的第一个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
 
1199 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Random Davis
Reply   •   1 楼
Random Davis    3 年前

从技术上讲,你只需要一次改变就能让它发挥作用; v3 是一个 tuple 共有3个值。你可以把它传递给 Vector 结果将是一个适当的 矢量 可以添加到其他向量的对象,如下所示:

v3 = Vector(Vector.fill_n(3,1))

正如我在评论中所说的 fill_n 方法不引用 self 参数,所以你应该 @staticmethod 在它上面。在这种情况下,这是不必要的,但它会丢弃IDE使用的任何类型的静态分析仪或短绒:

@staticmethod
    def fill_n(size, val):
        ...

考虑到这些,你的脚本运行良好。输出:

5, 4, 5
2, 3, 4
1, 1, 1
ShadowRanger
Reply   •   2 楼
ShadowRanger    3 年前

fill_n 很明显 预定的 Vector ,但在实现时,不会执行类似的操作,因此会出现类型冲突。使其成为具有 @classmethod ,您将得到您想要的结果,而无需进行其他更改:

@classmethod                 # Ensures it passes the class even when called on an instance
def fill_n(cls, size, val):  # Added initial parameter, cls, the actually class called on
    value=[val]*size
    return cls(value)  # Changed from tuple to cls which will be Vector (or a subclass)

一般来说, 全部的 替代构造函数应该是 @类方法 s具有 @staticmethod ,您将不会对子类友好,因为未修饰的方法会忽略 self / cls 它只在类而不是实例上被调用时才起作用(这使得从现有实例的类构造新实例变得更加困难),使用实例方法,您可以 不能 在课堂上说吧。