Fork me on GitHub

Python基础:深浅拷贝

对于数字、字符串深浅拷贝:

import copy
num = 0
copy_num = copy.copy(num)
print("These are normal copy").center(60,'*')
print(num,id(num))
print(copy_num,id(copy_num))
print("These are deep copy").center(60,'*')
deep_copy_num = copy.deepcopy(num)
print(num,id(num))
print(deep_copy_num,id(deep_copy_num))
*******************These are normal copy********************
(0, 3910788)	#原num id
(0, 3910788)	#浅拷贝 id
********************These are deep copy*********************
(0, 3910788)	#原num id
(0, 3910788)	#深拷贝 id

对于字典、元组、列表深浅拷贝:

import copy
dic = {
     "CPU":[80,],
     "IO":[80,],
     "Disk":[70,],
     "Memory":[70,],
 }

copy_dic = copy.copy(dic)
copy_dic["CPU"][0]=30
print("These are normal copy").center(60,'*')
print(dic,id(dic))
print(copy_dic,id(copy_dic))
print("These are deep copy").center(60,'*')
deepcopy_dic = copy.deepcopy(dic)
deepcopy_dic["CPU"][0]=40
print(dic,id(dic))
print(deepcopy_dic,id(deepcopy_dic))
*******************These are normal copy********************
({'Disk': [70], 'CPU': [30], 'IO': [80], 'Memory': [70]}, 39905584)    #原dic id
({'Disk': [70], 'CPU': [30], 'IO': [80], 'Memory': [70]}, 39906736)    #浅拷贝 id
********************These are deep copy*********************
({'Disk': [70], 'CPU': [30], 'IO': [80], 'Memory': [70]}, 39905584)    #原dic id
({'Disk': [70], 'CPU': [40], 'IO': [80], 'Memory': [70]}, 39907168)    #深拷贝 id

  由以上可以看出对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。

  对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。

  赋值,只是创建一个变量,该变量指向原来内存地址。

posted @ 2016-01-31 17:12  stefan.liu  阅读(324)  评论(0编辑  收藏  举报