Python class: Add a number to each element of a vector using __add__

advertisements

Suppose I have a vector (a_1, a_2, a_3, ... , a_n)

and I want to add a number to each element of my vector using the __add__ in python class.

Such that:

a = vector(7, 4, 2)

print a + 3

will output: (10, 7, 5)

Please help. What would be my code for this problem?

Thank you so much.


Here's a simple implementation:

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)

Output:

vector(10, 7, 5)

I assumed your (10, 7, 4) was meant to be (10, 7, 5)