在Python中,对象赋值在本质上是对对象的引用,当创建一个对象把它赋值给另一个变量的时候,Python并没有拷贝这个对象,而只是拷贝了这个对象的引用,这里通过程序,借用Python中的copy模块进一步理解深拷贝、浅拷贝和对象赋值有什么不同。 这里分两种情况: (1)、存在父对象和子对象 演示代码如下:
import copy
Dict = {'animal':'cat','num':[10,20,30],'color':'pink'}
Dict1_copy = Dict.copy()
Dict1_dcopy = copy.deepcopy(Dict)
Dict2 = Dict
Dict['num'][1] = 66
print('Dict:'+str(Dict))
print('Dict1_copy:'+str(Dict1_copy))
print('Dict1_dcopy:'+str(Dict1_dcopy))
print('Dict2:'+str(Dict2))
运行结果如下:  (2)、如果只存在父对象 演示代码如下:
import copy
Dict = {'animal':'cat','num':'10','color':'pink'}
Dict1_copy = Dict.copy()
Dict1_dcopy = copy.deepcopy(Dict)
Dict2 = Dict
Dict['animal'] = 'dog'
print('Dict:'+str(Dict))
print('Dict1_copy:'+str(Dict1_copy))
print('Dict1_dcopy:'+str(Dict1_dcopy))
print('Dict2:'+str(Dict2))
运行结果如下:  由此可以看出,数据修改后,深拷贝一定不会被修改;浅拷贝如果有所谓父对象和子对象即嵌套,第二层可以被修改,不同于深拷贝,如果不存在嵌套,只有父对象,虽然本质上与深拷贝不同,但不会被修改;对象赋值,则是引用,跟着修改而改变。 下面举个简单例子,改变特定的数值,对其它数值的影响:
Dict_A = {
"A":11,
"B":22,
"C":[33,44,55]
}
Dict_B = Dict_A
Dict_C = Dict_A.copy()
Dict_D = copy.deepcopy(Dict_A)
print('Dict_A:'+str(Dict_A))
print('Dict_B:'+str(Dict_B))
print('Dict_C:'+str(Dict_C))
print('Dict_D:'+str(Dict_D))

Dict_D['A'] = 99
print('Dict_A:'+str(Dict_A))
print('Dict_B:'+str(Dict_B))
print('Dict_C:'+str(Dict_C))
print('Dict_D:'+str(Dict_D))

Dict_B['A'] = 77
print('Dict_A:'+str(Dict_A))
print('Dict_B:'+str(Dict_B))
print('Dict_C:'+str(Dict_C))
print('Dict_D:'+str(Dict_D))

Dict_C['A'] = 88
print('Dict_A:'+str(Dict_A))
print('Dict_B:'+str(Dict_B))
print('Dict_C:'+str(Dict_C))
print('Dict_D:'+str(Dict_D))

Dict_D['A'] = 99
print('Dict_A:'+str(Dict_A))
print('Dict_B:'+str(Dict_B))
print('Dict_C:'+str(Dict_C))
print('Dict_D:'+str(Dict_D))

Dict_C['C'][1] = 100
print('Dict_A:'+str(Dict_A))
print('Dict_B:'+str(Dict_B))
print('Dict_C:'+str(Dict_C))
print('Dict_D:'+str(Dict_D))

Dict_C['C'][1] = 101
print('Dict_A:'+str(Dict_A))
print('Dict_B:'+str(Dict_B))
print('Dict_C:'+str(Dict_C))
print('Dict_D:'+str(Dict_D))

Dict_C['C'][1] = 102
print('Dict_A:'+str(Dict_A))
print('Dict_B:'+str(Dict_B))
print('Dict_C:'+str(Dict_C))
print('Dict_D:'+str(Dict_D))

Dict_D['C'][1] = 104
print('Dict_A:'+str(Dict_A))
print('Dict_B:'+str(Dict_B))
print('Dict_C:'+str(Dict_C))
print('Dict_D:'+str(Dict_D))

|