浅述python中深浅拷贝原理
前言
在c++中参数传递有两种形式:值传递和引用传递。这两种方式的区别我不在此说,自行补上,如果你不知道的话。我先上python代码,看完我们总结一下,代码如下:
# copy module import import copy # number and string a = 12 a1 = a a2 = copy.copy(a) a3 = copy.deepcopy(a) # look addr print("==========number=======") print(id(a)) print(id(a1)) print(id(a2)) print(id(a3)) s = '12345' s1 = s s2 = copy.copy(s) s3 = copy.deepcopy(s) # look addr print("==========String=======") print(id(s)) print(id(s1)) print(id(s2)) print(id(s3)) # others target = { 'name': 'ckmike', 'age': 25, 'boxes':[ 'LV', 'Prada', 'KUQI' ] } target1 = target target2 = copy.copy(target) target3 = copy.deepcopy(target) print("==========dict-1=======") print(id(target)) print(id(target1)) print(id(target2)) print(id(target3)) print("==========dict-2=======") print(id(target['boxes'])) print(id(target1['boxes'])) print(id(target2['boxes'])) print(id(target3['boxes']))
输出结果:
==========number=======
10943360
10943360
10943360
10943360
==========String=======
140567123944648
140567123944648
140567123944648
140567123944648
==========dict-1=======
140567124625088
140567124625088
140567124625160
140567123938760
==========dict-2=======
140567099339272
140567099339272
140567099339272
140567099339464
总结:
对于数值、字符串而言,不管是赋值符号还是浅拷贝、深拷贝,都是引用的内存中的同一份值,变量指向同一地址。
对于非数值非字符串而言,浅拷贝只会拷贝对象的第一层,深拷贝则会把所有层都进行拷贝。