hiccup
hiccup

Reputation: 29

Python giving me two different results while performing the same operation on the same objects twice

I created a class vector2D in python with a method to add vectors. Then I used it to add the same vectors twice and got different results. Why did that happen?

Here's the code:

class vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        self.x += other.x
        self.y += other.y
        return self.x, self.y   

#Creating vector objects
v1 = vector2D(2, 3)
v2 = vector2D(4, 8)

#using the redefined addition operator to add vector objects
v = v1 + v2       #output: (6, 11)
print(v)

#Adding again
v = v1 + v2      #output: (10, 19)
print(v)

Upvotes: 1

Views: 254

Answers (2)

Charif DZ
Charif DZ

Reputation: 14751

Your doing in place assignment, when you do this

   self.x += other.x

you are changing the x attribute of the object it self, so when you do the second addition the x is changed.

One more thing __add__ should return an instance of the same class, Developer when using your class they will expect when they add vector2d to another vector2d they get a vector2d but you are returning a tuple:

class vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return self.__class__(self.x + other.x, self.y + other.y)

So when you add vector2D + vector2D you get vector2D instance.

Upvotes: 3

h4z3
h4z3

Reputation: 5478

You both add the vectors in place and return the result!

    def __add__(self, other):
        self.x += other.x
        self.y += other.y
        return self.x, self.y   

This changes first vector's parameters! += means self.x = self.x + other.x.

Do this instead:

    def __add__(self, other):
        result_x = self.x + other.x
        result_y = self.y + other.y
        return result_x, result_y

Upvotes: 3

Related Questions