马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
问题来自第033讲,提到可变序列扩充之后id不变,但是我发现扩充的方法如果不同,id也会变化
按照小甲鱼提到的方法,用列表,a *= 2这样扩充走一遍,这样之后确实id不变没问题。但问题是,如果扩充方法变成 b = b * 2,id就变了,为什么酱紫?请教各位前辈!
a = [1, 2, 3]
id(a)
1989153609152
a *= 2
a
[1, 2, 3, 1, 2, 3]
id(a)
1989153609152
b = [1, 2, 3]
id(b)
1989186185216
b = b * 2
id(b)
1989186186688
根据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改变
|