Python中表达式x += y和x = x+y 的区别详解
作者:hooog 时间:2022-02-24 04:11:19
前言
本文主要给大家介绍的是关于Python中表达式x += y和x = x+y 区别的相关内容,分享出来供大家参考学习,下面来看看详细的介绍:
直接看下面代码:
x +=y
In [66]: id(a)
Out[66]: 4476839480
In [67]: id(b)
Out[67]: 4476839480
In [68]: a = [1, 2, 3]
In [69]: b = a
In [70]: id(a)
Out[70]: 4477149984
In [71]: id(b)
Out[71]: 4477149984
In [72]: a += [4, 5, 6]
In [73]: a
Out[73]: [1, 2, 3, 4, 5, 6]
In [74]: b
Out[74]: [1, 2, 3, 4, 5, 6]
In [75]: id(a)
Out[75]: 4477149984
In [76]: id(b)
Out[76]: 4477149984
x = x + y
In [77]: a = [1, 2, 3]
In [78]: b = a
In [79]: id(a)
Out[79]: 4476686208
In [80]: id(b)
Out[80]: 4476686208
In [81]: a = a + [4, 5, 6]
In [82]: a
Out[82]: [1, 2, 3, 4, 5, 6]
In [83]: b
Out[83]: [1, 2, 3]
In [84]: id(a)
Out[84]: 4477187640
In [85]: id(b)
Out[85]: 4476686208
可以看出对于可变对象而言 x = x + y 这种形式已经改变了x的指向,而不是"inplace"的修改。
使用dis模块进行一下验证。
In [86]: def foo(x, y):
...: x += y
...: return x
...:
In [87]: def foo(x, y):
...: x += y
...:
In [88]: def foo2(x, y):
...: x = x + y
...:
In [89]: dis.dis(foo)
2 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 INPLACE_ADD
7 STORE_FAST 0 (x)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
In [90]: dis.dis(foo2)
2 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 BINARY_ADD
7 STORE_FAST 0 (x)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
可以看到字节码是不同的:
+= 对应 INPLACE_ADD
对应BINARY_ADD
注意:以上仅适用于CPython实现。
来源:https://hooog.tk/posts/inplace-binary-add/
标签:python,表达式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python time模块计算时间之间的差距(练习题)
2021-09-05 02:24:03
python通过百度地图API获取某地址的经纬度详解
2021-11-06 12:14:45
![](https://img.aspxhome.com/file/2023/6/66456_0s.png)
python实现简单中文词频统计示例
2022-04-17 16:54:35
![](https://img.aspxhome.com/file/2023/7/101557_0s.png)
使用ajax开发的五大误区
2008-09-03 12:46:00
Python 用__new__方法实现单例的操作
2023-05-22 08:22:41
Laravel中常见的错误与解决方法小结
2023-09-09 19:38:37
![](https://img.aspxhome.com/file/2023/2/56292_0s.jpg)
python从入门到实践之组合数据类型
2021-09-02 17:53:54
python中arrow库用法大全
2021-08-25 06:48:44
![](https://img.aspxhome.com/file/2023/4/104804_0s.png)
细品Dreamweaver MX 内建FW技术
2008-06-04 09:41:00
Anaconda入门使用总结
2023-02-06 20:11:18
![](https://img.aspxhome.com/file/2023/9/107949_0s.png)
go语言LeetCode题解720词典中最长的单词
2023-08-05 19:46:04
Python设计模式之工厂模式简单示例
2022-10-06 13:22:38
![](https://img.aspxhome.com/file/2023/1/75341_0s.png)
关于Tensorflow中的tf.train.batch函数的使用
2023-11-04 19:49:54
Python爬虫爬取ts碎片视频+验证码登录功能
2023-03-23 01:39:23
![](https://img.aspxhome.com/file/2023/7/70207_0s.png)
insert select与select into 的用法使用说明
2012-01-05 18:47:58
基于Python实现自动扫雷详解
2023-09-07 23:31:20
![](https://img.aspxhome.com/file/2023/9/86389_0s.gif)
Python join()函数原理及使用方法
2021-01-17 18:37:08
网站设计应当让用户选,别让用户想
2008-03-19 12:01:00
python基于pygame实现飞机大作战小游戏
2021-04-27 07:59:17
![](https://img.aspxhome.com/file/2023/8/81528_0s.jpg)
Python实现基于HTTP文件传输实例
2021-10-23 13:24:53