Python类:使用__add__为向量中的每个元素添加一个数字

时间:2013-12-17 03:15:51

标签: python class add

假设我有一个向量(a_1,a_2,a_3,...,a_n)

我希望使用python类中的__add__为我的向量的每个元素添加一个数字。

这样:

a =向量(7,4,2)

打印+ 3

将输出:(10,7,5)

请帮忙。这个问题的代码是什么?

非常感谢你。

2 个答案:

答案 0 :(得分:2)

这是一个简单的实现:

class vector(object):

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

    def __add__(self, other):
        if not isinstance(other, int):
            raise TypeError("Cannot add {} with {}".format(type(self), type(other)))
        return vector(*(arg + other for arg in self.args))

    def __repr__(self):
        return "vector({})".format(", ".join(map(str, self.args)))


a = vector(7, 4, 2)

print a + 3  # (10, 7, 5)

<强>输出:

vector(10, 7, 5)

我认为您的(10, 7, 4)原本是(10, 7, 5)

答案 1 :(得分:0)

class Vector():

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

    def __add__(self, other):
        return tuple(map(lambda x:x+other,self.args))

a = Vector(1,2,3,4,5)
print a+3