当将一个变量赋给另一个变量时,它们指向同一个对象。那么,如何在变量仍然指向同一个对象的情况下更改其中一个变量的值呢?
a = 10
b = a
a -= 1
print(b) #expect to print 9 but it print 10
如何在不改变变量id的情况下在python中重新赋值?
发布于 2018-07-14 15:33:13
变量没有id,id属于一个对象。整数,例如: 10,9是分离的和不可变的对象,'a','b‘变量只是引用。id(a)实际上给出了被引用对象的id。对象“%10”不能就地变异。
id(10), id(9)
Out[16]: (10943296, 10943264)
In [17]: a,b=10,10
In [18]: id(a),id(b)
Out[18]: (10943296, 10943296)
In [19]: b=a-1
In [20]: id(b)==id(9)
Out[20]: True
然而,列表是可变的对象,可以通过操作符(当然,还有它们的方法,例如: append,extend)进行适当的更改:
l=[10,5]
In [29]: id(l),id(l[0]),id(l[1])
Out[29]: (139638954619720, 10943296, 10943136)
In [30]: id(l[0])==id(10)
Out[30]: True
In [31]: l=[10,5] # a new list object created, though the content is the same
In [32]: id(l)
Out[32]: 139638920490248
In [33]: l[:]=["a","b"] # in place changes
In [34]: id(l)
Out[34]: 139638920490248
https://stackoverflow.com/questions/51336185
复制相似问题