a = [81, 82, 83]
b = a
print(a is b) #prints True
这就是这里实际发生的事情:
对于类似的东西:
a = [81,82,83]
b = [81,82,83]
print(a is b) # False
print(a == b) #True, as == only checks value equality
In [24]: import sys
In [25]: a=[1,2,3]
In [26]: sys.getrefcount(a) #number of references to [1,2,3] are 2
Out[26]: 2
In [27]: b=a #now b also points to [1,2,3]
In [28]: sys.getrefcount(a) # reference to [1,2,3] got increased by 1,
# as b now also points to [1,2,3]
Out[28]: 3
In [29]: id(a)
Out[29]: 158656524 #both have the same id(), that's why "b is a" is True
In [30]: id(b)
Out[30]: 158656524
何时使用该copy
模块:
In [1]: a=[1,2,3]
In [2]: b=a
In [3]: id(a),id(b)
Out[3]: (143186380, 143186380) #both point to the same object
In [4]: b=a[:] #now use slicing, it is equivalent to b=copy.copy(a)
# or b= list(a)
In [5]: id(a),id(b)
Out[5]: (143186380, 143185260) #as expected both now point to different objects
# so now changing one will not affect other
In [6]: a=[[1,2],[3,4]] #list of lists
In [7]: b=a[:] #use slicing
In [8]: id(a),id(b) #now both point to different object as expected
# But what about the internal lists?
Out[8]: (143184492, 143186380)
In [11]: [(id(x),id(y)) for (x,y) in zip(a,b)] #so internal list are still same objects
#so doing a[0][3]=5, will changes b[0] too
Out[11]: [(143185036, 143185036), (143167244, 143167244)]
In [12]: from copy import deepcopy #to fix that use deepcopy
In [13]: b=deepcopy(a)
In [14]: [(id(x),id(y)) for (x,y) in zip(a,b)] #now internal lists are different too
Out[14]: [(143185036, 143167052), (143167244, 143166924)]
更多细节:
In [32]: def func():
....: a=[1,2,3]
....: b=a
....:
....:
In [34]: import dis
In [35]: dis.dis(func)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 BUILD_LIST 3
12 STORE_FAST 0 (a) #now 'a' poits to [1,2,3]
3 15 LOAD_FAST 0 (a) #load the object referenced by a
18 STORE_FAST 1 (b) #store the object returned by a to b
21 LOAD_CONST 0 (None)
24 RETURN_VALUE
In [36]: def func1():
....: a=[1,2,3]
....: b=[1,2,3]
....:
....:
In [37]: dis.dis(func1) #here both a and b are loaded separately
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 BUILD_LIST 3
12 STORE_FAST 0 (a)
3 15 LOAD_CONST 1 (1)
18 LOAD_CONST 2 (2)
21 LOAD_CONST 3 (3)
24 BUILD_LIST 3
27 STORE_FAST 1 (b)
30 LOAD_CONST 0 (None)
33 RETURN_VALUE