#!/usr/bin/env python3import copy #copy 有两种#浅copy#copy.copy() #深copy#copy.deepcopy() ‘‘‘######################### ## 字符串于数字的copy ## ######################### #内存地址相同,字符串于数字的copy永远都是用的内存中的唯一的地址#a = 123123#b = 123123#print(id(a))#print(id(b)) #a1 = 123123#b1 = copy.copy(a1)#print(id(b1)) a2 = 123123b2 = copy.deepcopy(a2)print(id(a2))‘‘‘ #其他,元组、列表、字典的copy dic = {‘name‘:‘andy‘,‘age‘:18,‘job‘:‘IT‘,‘pro‘:[1,2,3,4,5]}#浅copydic2 = copy.copy(dic)print(dic)print(id(dic))print(dic2)print(id(dic2)) #深copydic2 = copy.deepcopy(dic)print(dic)print(id(dic))print(dic2)print(id(dic2)) #实例,网络模版#假设如下是网络模版,有很多机器都要使用,重复创建太傻了,所以就用到了copy #浅copy会出错,把不需要修改数据已经修改了,会连同模版一起修改掉ds = { ‘cup‘:[80,], ‘mem‘:[80,], ‘disk‘:[80,]}#print(‘浅copy‘)# print(ds)# new_ds = copy.copy(ds)# new_ds[‘cup‘][0] = 50# print(new_ds)# print(ds) #深copy只修改需要的数据,不会对模版造成影响print(‘深copy‘)print(ds)new_ds = copy.deepcopy(ds)new_ds[‘cup‘][0] = 50print(new_ds)print(ds)
时间: 2024-11-10 15:28:59