求助,关于python中__add__和__iadd__的疑问

weixin_41655840 2018-01-20 04:05:54
代码:
import time
t = time.time()
a = '1'
b = '2'
for i in range(1000000):
b += a
print(time.time() - t)

t1 = time.time()
a = '1'
b = '2'
for i in range(1000000):
b = b + a
print(time.time() - t1)

执行结果
0.6396
0.6240

按照我的理解,字符串是没有iadd这个方法的,会默认调用add这个方法,但是运行的结果却不一致,
求大神解答!!
...全文
813 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
混沌鳄鱼 2018-01-20
  • 打赏
  • 举报
回复

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
oyljerry 2018-01-20
  • 打赏
  • 举报
回复
运行时间受很多因素影响。同时看看字节码是否相同。

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧