37,721
社区成员
发帖
与我相关
我的任务
分享
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def foo():
a = '1'
b = '2'
b += a
return b
>>> def bar():
a = '1'
b = '2'
b = b + a
return b
>>> import dis
>>> dis.dis(foo)
2 0 LOAD_CONST 1 ('1')
2 STORE_FAST 0 (a)
3 4 LOAD_CONST 2 ('2')
6 STORE_FAST 1 (b)
4 8 LOAD_FAST 1 (b)
10 LOAD_FAST 0 (a)
12 INPLACE_ADD
14 STORE_FAST 1 (b)
5 16 LOAD_FAST 1 (b)
18 RETURN_VALUE
>>> dis.dis(bar)
2 0 LOAD_CONST 1 ('1')
2 STORE_FAST 0 (a)
3 4 LOAD_CONST 2 ('2')
6 STORE_FAST 1 (b)
4 8 LOAD_FAST 1 (b)
10 LOAD_FAST 0 (a)
12 BINARY_ADD
14 STORE_FAST 1 (b)
5 16 LOAD_FAST 1 (b)
18 RETURN_VALUE
>>>
看到没有,
b = b + a 被编译成字节码后是 BINARY_ADD
而
b += a 被编译成的字节码是 INPLACE_ADD
这个是操作符说明文档
https://docs.python.org/3/library/operator.html#operator.iadd
For immutable targets such as strings, numbers, and tuples, the updated value is computed, but not assigned back to the input variable
这个是pep关于加法操作符实现
https://www.python.org/dev/peps/pep-0203/
这个是python加法等运算实现的c源码
https://github.com/python/cpython/blob/master/Python/ceval.c
https://github.com/python/cpython/blob/master/Objects/abstract.c