鱼C论坛

 找回密码
 立即注册
查看: 1152|回复: 3

[已解决]关于可变与不可变序列的id问题

[复制链接]
发表于 2022-7-3 11:01:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
问题来自第033讲,提到可变序列扩充之后id不变,但是我发现扩充的方法如果不同,id也会变化

按照小甲鱼提到的方法,用列表,a *= 2这样扩充走一遍,这样之后确实id不变没问题。但问题是,如果扩充方法变成 b = b * 2,id就变了,为什么酱紫?请教各位前辈!

  1. a = [1, 2, 3]
  2. id(a)
  3. 1989153609152
  4. a *= 2
  5. a
  6. [1, 2, 3, 1, 2, 3]
  7. id(a)
  8. 1989153609152

  9. b = [1, 2, 3]
  10. id(b)
  11. 1989186185216
  12. b = b * 2
  13. id(b)
  14. 1989186186688
复制代码


最佳答案
2022-7-3 13:41:29
根据python官网https://docs.python.org/3.6/reference/simple_stmts.html#augmented-assignment-statements
里面提到了
An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

简单来说,就是+=, -=, *=, /=这些运算符和a= a+b,a= a-b, a= a*b, a= a/b有所不同。前者直接改变原对象,在你的例子中, a *= 2直接改变a。后者会创造一个新对象,并取代原来的对象,在你的例子中,b = b * 2,实际上是创造了一个新的列表,赋给b,取代了原来的列表[1, 2, 3]。所以a的id不变,b在运算过后实际指向一个新对象,所以id改变
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-7-3 13:41:29 | 显示全部楼层    本楼为最佳答案   
根据python官网https://docs.python.org/3.6/reference/simple_stmts.html#augmented-assignment-statements
里面提到了
An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

简单来说,就是+=, -=, *=, /=这些运算符和a= a+b,a= a-b, a= a*b, a= a/b有所不同。前者直接改变原对象,在你的例子中, a *= 2直接改变a。后者会创造一个新对象,并取代原来的对象,在你的例子中,b = b * 2,实际上是创造了一个新的列表,赋给b,取代了原来的列表[1, 2, 3]。所以a的id不变,b在运算过后实际指向一个新对象,所以id改变
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-7-3 13:45:09 | 显示全部楼层
另外给个小建议,这个东西本来我是不懂的,google一下后就找到了相关的问题。所以要懂得善用搜索引擎
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-7-3 16:57:43 | 显示全部楼层
鱼cpython学习者 发表于 2022-7-3 13:45
另外给个小建议,这个东西本来我是不懂的,google一下后就找到了相关的问题。所以要懂得善用搜索引擎{:10_2 ...

感谢提醒,一开始不知道怎么去搜索这个问题嘻嘻嘻,感谢鱼油!渔溪!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-19 20:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表