Can you plz explain me data flow of this code in the line when the two objects get add and how the "+ operator overloaded | SoloLearn: Learn to code for FREE!

0

Can you plz explain me data flow of this code in the line when the two objects get add and how the "+ operator overloaded

class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second print(result.x) print(result.y)

2/21/2017 12:53:01 PM

Chandan Kumar Sahoo

1 Answer

New Answer

+2

Overloading the magic method __add__ tells Python how to act when you use the plus operator on certain classes. If you add two object of Vector2D class, it goes through the class definition and looks for the overloading, then acts on it like you wanted (in this case it adds x-s and y-s of both vectors). While carrying out this x+x and y+y operation, it goes by data type-specific methods - in this case the data type is integer, so it simply adds the numbers and returns the arithmetic result. Now, if the vector parameters (all of them) were strings, the magic method would also works but it would perform the addition default for strings - it would concatenate them (but still x to x and y to y ;)