如何使用__add__方法在python中添加2个向量?

时间:2019-04-02 23:56:35

标签: python-3.x

我想使用 add

方法添加两个向量

我尝试了此代码,但是它不起作用

class vector(object):

    def __init__(self, *args):
        self.args = args

    def __add__(self, *other):
        a = [arg + other for arg, other in
                        list(zip(self.args, self.other))]
        return vector(*a)
    def __repr__(self):
        return self.args

v1 = vector(1, 4, 8, 9),
v2 = vector(5, 3, 2, 1)

产生:

Traceback (most recent call last):
    File "<pyshell#24>", line 1, in <module>
    v1 +v2

File "C:/Users/Rouizi/Desktop/b.py", line 8, in __add__
    list(zip(self.args, self.other))]
AttributeError: 'vector' object has no attribute 'other'

1 个答案:

答案 0 :(得分:1)

我对您的代码进行了稍微的修改。跟随评论。

# class names should use CapWords convention (https://www.python.org/dev/peps/pep-0008/#naming-conventions)
class Vector:

    def __init__(self, *args):
        self.args = args

    # addition is normally a binary operation between self and other object
    def __add__(self, other):
        # other.args is the correct analog of self.args
        a = [arg1 + arg2 for arg1, arg2 in zip(self.args, other.args)]
        return self.__class__(*a)

    # __repr__ and __str__ must return string
    def __repr__(self):
        return self.__class__.__name__ + str(self.args)


v1 = Vector(1, 4, 8, 9)
v2 = Vector(5, 3, 2, 1)

print(v1)
print(v2)
print(v1 + v2)
print(v1 + v1 + v2 + v2)

输出:

Vector(1, 4, 8, 9)
Vector(5, 3, 2, 1)
Vector(6, 7, 10, 10)
Vector(12, 14, 20, 20)

我也使用self.__class__代替Vector,并使用self.__class__.__name__代替"Vector"-这允许更改类名而不更改其代码。