Python __sub__ usage with class instances
__sub__ is supposed to be the magic method equivalent of
- arithmetic operator, so not sure why youre adding them…
That aside, when you do
p1 - p2, it is the same as
__sub__ function is invoked on
p1, the calculation made and the new
Point object returned.
Now you edited the question, the answer is simple:
p1 = Point(3, 4) p2 = Point(1, 2) result = p1-p2
You have two points as arguments
self, other, so, self, obviously in your example would be
p1, and other is
p2, after doing all the calculation, you return a new Point, so,
p2 are not modified.
The most rare thing, is that you call it
__sub__, but indeed, you are actually adding! I mean, please… either change the method definition and replace + by -, or change
__sub__… just a piece of advice.