开发者

python int doesn't have __iadd__() method?

开发者 https://www.devze.com 2023-01-23 13:34 出处:网络
I know this is bad practice: >>> a = 5 >>> a.__radd__(5) 10 >>> a 5 >>> a.__iadd__(5)

I know this is bad practice:

>>> a = 5
>>> a.__radd__(5)
10
>>> a
5
>>> a.__iadd__(5)
Traceback (most recent call开发者_JAVA技巧 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消