标签:
1.针对字符和数字的赋值,深拷贝与浅拷贝
import copy
s1 = "abcdefg"
s2 = s1
print (id(s1))
print (id(s2))
结果:
24266496
24266496
结论:对于赋值操作,内存地址是一致的。
import copy
s1 = "abcdefg"
s2 = copy.copy(s1)
print (id(s1))
print (id(s2))
结果:
5129984
5129984
结论:对于浅拷贝,内存地址也是一致的
import copy
s1 = "abcdefg"
s2 = copy.deepcopy(s1)
print (id(s1))
print (id(s2))
结果:
24069888
24069888
结论:对于深拷贝,内存地址也是一致的
2.针对列表,元祖与字典的赋值,深拷贝与浅拷贝
import copy
n1 = {"k1":[‘v11‘,‘v12‘,(‘v131‘,‘v132‘)],"k2":(‘v21‘,‘v22‘,‘v23‘),"k3":"v31"}
n2 = n1
print (id(n1))
print (id(n2))
print (id(n1[‘k1‘][0]))
print (id(n2[‘k1‘][0]))
结果:
24617448
24617448
24594208
24594208
结论:对于赋值操作,n2跟n1是同一个指向关系
import copy
n1 = {"k1":[‘v11‘,‘v12‘,(‘v131‘,‘v132‘)],"k2":[‘v21‘,‘v22‘,‘v23‘],"k3":"v31"}
n2 = copy.copy(n1)
print (id(n1))
print (id(n2))
print (id(n1[‘k1‘]))
print (id(n2[‘k1‘]))
结果:
30712296
30965472
31193048
31193048
结论:对于浅拷贝,只有第一层是在内存中新建内存区域保存指向关系
import copy
n1 = {"k1":[‘v11‘,‘v12‘,(‘v131‘,‘v132‘)],"k2":[‘v21‘,‘v22‘,‘v23‘],"k3":"v31"}
n2 = copy.deepcopy(n1)
print (id(n1))
print (id(n2))
print (id(n1[‘k1‘]))
print (id(n2[‘k1‘]))
print (id(n1[‘k1‘][0]))
print (id(n2[‘k1‘][0]))
结果:
21144040
21147600
24639488
24638088
21120800
21120800
结论:对于深拷贝,拷贝深层的内部结构
深浅拷贝的应用:
import copy
dic = {
"cpu":[80,],
"mem":[80,],
"disk":[80,]
}
print (dic)
new_dic = copy.deepcopy(dic)
new_dic["cpu"][0] = 50
print (dic)
print (new_dic)
结果:
{‘disk‘: [80], ‘mem‘: [80], ‘cpu‘: [80]}
{‘disk‘: [80], ‘mem‘: [80], ‘cpu‘: [80]}
{‘disk‘: [80], ‘mem‘: [80], ‘cpu‘: [50]}
结论:原来的阀值不修改,新添加的服务器阀值被重新设置为了50。如果使用浅拷贝,新建阀值都将被改变。
标签:
原文地址:http://www.cnblogs.com/python-study/p/5448717.html