Sam Rohn
Sam Rohn

Reputation: 369

Python __sub__ usage with class instances

class Point:

    def __init__(self, x = 0, y = 0):
      self.x = x
      self.y = y

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

p1 = Point(3, 4)
p2 = Point(1, 2)
result = p1-p2
print(result.x, result.y) # prints (4,6)

Can anyone explain how the above code works. Can't get my head around it. I understand that __sub__ is an operator overloader in python and intercepts the p1-p2 call. But how does it work with two separate instances of class ?

Upvotes: 5

Views: 17363

Answers (2)

developer_hatch
developer_hatch

Reputation: 16224

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.

Upvotes: 2

cs95
cs95

Reputation: 402563

__sub__ is supposed to be the magic method equivalent of - arithmetic operator, so not sure why you're 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.

Upvotes: 9

Related Questions