5

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?

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Austin Richardson
  • 8,078
  • 13
  • 43
  • 49

2 Answers2

7

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.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 3
    Which is of course because integers are immutable, i.e. there's no way an integer object can increment itself. –  Nov 03 '10 at 15:37
  • `a += 5` does not become `a = a + 5`. It can call `__add__`, but only if `__iadd__` doesn't exist (as Paulo Scardino mentions.) – Thomas Wouters Nov 03 '10 at 15:39
  • 1
    @Thomas Wouters: It may not always be transformed into that, but it does for the case the OP asked about, namely "if an `int` object doesn't have `__iadd__`, then how does `+=` work?" -- as it would with other immutable types that have an `__add__` method. – martineau Nov 03 '10 at 17:11
3

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.

Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153