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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With