Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of addition expressions matter in Python?

Tags:

python

methods

This sounds kind of stupid but I'm not talking about 1 + 2 = 2 + 1. I am talking about where an object with an __add__ method is added to a number. An example will be:

>>> 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 like normal

like image 706
jkd Avatar asked Dec 15 '22 15:12

jkd


1 Answers

Addition isn't assumed to be commutative - for example, [1] + [2] != [2] + [1] - so there's a separate method you need to implement when your object is on the right side of a + and the thing on the left doesn't 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's type.

Similar methods exist for all the other binary operations, all named by sticking an r in the same place.

like image 125
user2357112 supports Monica Avatar answered Feb 14 '23 05:02

user2357112 supports Monica