Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python int doesn't have __iadd__() method?

I know this is bad practice:

>>> a = 5
>>> a.__radd__(5)
10
>>> a
5
>>> a.__iadd__(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__iadd__'

Out of curiosity, if an int object doesn't have __iadd__, then how does += work?

like image 201
Austin Richardson Avatar asked Nov 03 '10 15:11

Austin Richardson


2 Answers

Out of curiosity, if an int object doesn't have __iadd__, then how does += work?

a += 5

Becomes

a = a + 5

Because there's no __iadd__ for immutable objects.

This is (in effect)

a = a.__add__( 5 )

And works nicely. A new int object is created by __add__.

Some of the rules are here http://docs.python.org/reference/datamodel.html#coercion-rules.

like image 103
S.Lott Avatar answered Sep 28 '22 03:09

S.Lott


If an object does not have __iadd__, __add__ will be used. Method __iadd__ is suposed to be an optimized inplace __add__ case, it is not mandatory.

like image 29
Paulo Scardine Avatar answered Sep 28 '22 02:09

Paulo Scardine