Is there an order of addition expressions in Python?

That sounds silly, but I'm not talking about 1 + 2 = 2 + 1. I am talking about where an object with a method is __add__added to a number. An example is:

>>> class num:
...     def __add__(self,x):
...             return 1+x
... 
>>> n = num()
>>> 1+n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'instance'
>>> n+1
2
>>>

I don’t understand why the first one returns an error, and the second one works as usual

+4
source share
2 answers

An add-on is not considered commutative - for example, [1] + [2] != [2] + [1]- so there is a separate method that you need to implement when your object is on the right side +, and the thing on the left is not to know how to handle it.

def __radd__(self, other):
    # Called for other + self when other can't handle it or self's
    # type subclasses other type.

Similar methods exist for all other binary operations, they are all called inserting rin the same place.

+8

, .

__add__ int (, , , , ); __add__ num.

__add__ , Python , user2357112.

+4

All Articles