Z
Z
zlodiak2019-01-31 21:47:50
Python
zlodiak, 2019-01-31 21:47:50

When does __sub__() fire?

There is this code:

class Number:
  def __init__(self, start):
    self.data = start
  def __sub__(self, other):
    return Number(self.data - other)

X = Number(5)
Y = X - 2

print(Y.data)

It redefines the subtraction operator. And in general it is clear what is happening in the presented code. But the next line is not clear: Can you please explain why the entry X - 2 calls the __sub__() method? Is there any technical explanation for this or you just need to remember that if: 1. write an instance of the class (X) 2. after it write a minus (-) 3. after it write some other instance of the class , then the __sub__() method will work , whose argument in some unknown but reliable way will get __str__() representation of the class instance from point 3 (that is, the number 2).
Y = X - 2

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question