补充一个,
从字节码看的话,
>>> def fun():
... a = 1
... a += 2
...
import dis
>>> dis.dis(fun)
2 0 LOAD_CONST 1 (1)
3 STORE_FAST 0 (a)
3 6 LOAD_FAST 0 (a)
9 LOAD_CONST 2 (2)
12 INPLACE_ADD
13 STORE_FAST 0 (a)
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
==========================================================
>>> def fun2():
... a = 1
... a = a+2
...
>>> dis.dis(fun2)
2 0 LOAD_CONST 1 (1)
3 STORE_FAST 0 (a)
3 6 LOAD_FAST 0 (a)
9 LOAD_CONST 2 (2)
12 BINARY_ADD
13 STORE_FAST 0 (a)
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
也可以看出=是binary add, +=是inplace add,也可以理解.
还有一个就是当不可变对象容器(tuple)中使用了可变对象元素的话,如
>>> t = (1,2,[2,3])
>>> t = (1,2,[2,3])
>>> t[2] = t[2] + [3,3]
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>> t
(1, 2, [2, 3])
============================
>>> t[2] += [3,3]
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>> t
(1, 2, [2, 3, 3, 3])
会发现虽然报错结果是相同的,但是执行t[2]+= 之后t[2]在赋值操作之前已经被改变.
“增量赋值不是一个原子操作。虽然抛出了异常,但还是完成了操作”
摘录来自: [巴西] Luciano Ramalho. “流畅的Python”。
摘录来自: [巴西] Luciano Ramalho. “流畅的Python”。 iBooks.