hkj447
hkj447

Reputation: 737

Python Class method: Subtracting two vectors

I have a custom vector class:

class VectorND:

    def __init__(self, *args, max=0):
        self.args = args
        max = len(args)
        self.max = max

    def __add__(self, x):
        if len(x.args) != len(self.args):
            raise Exception("Vectors are not same length")
        sum_coords = []
        for i in range(self.max):
            h = self.args[i] + x.args[i]
            sum_coords.append(h)
        new_coords = tuple(sum_coords)
        return VectorND(new_coords)
        
    def __subtract__(self, x):
        if len(x.args) != len(self.args):
            raise Exception("Vectors are not same length")
        sum_coords = []
        for i in range(self.max):
            h = self.args[i] - x.args[i]
            sum_coords.append(h)
        new_coords = tuple(sum_coords)
        return VectorND(new_coords)

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if self.n >= self.max:
            raise StopIteration
        entry = self.args[self.n]
        self.n += 1
        return entry

    def __str__(self):
        return "Vector: {[0]}".format(self.args)

Here, I am attempting to represent vector subtraction, but I get the following error when running this bit of code:

vec1= VectorND(1,2,3)
vec2 = VectorND(3,4,5)
vec3 = vec1 + vec2
print(vec3)

vec4 = vec2 - vec1
print(vec4)

>>>TypeError: unsupported operand type(s) for -: 'VectorND' and 'VectorND'

vec3 produces the correct result of (4,6,8); however, vec4 throws the TypeError. I am not sure why this is happening as the only difference between the add and subtract method is, well, subtracting the entries of the tuple. What is the nuance between these two different methods that is causing this error?

Upvotes: 1

Views: 445

Answers (1)

Sai Prashanth
Sai Prashanth

Reputation: 306

your function __add__() is an overloaded form of predefined function in python, which is mapped to "+" operator. however __subtract__() is not mapped to any operator.

Instead try using __sub__() as it is mapped to "-" operator.

Upvotes: 3

Related Questions