Python __sub__ usage with class instances

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 p1.__sub__(p2). The __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, p1 and p2 are not modified.

Important advice

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.

Python __sub__ usage with class instances

Leave a Reply

Your email address will not be published.