深浅拷贝
1. 对于字符串和数字而言,赋值与深浅拷贝无意义,因为其内存永远指向同一地址
1.赋值:
>>>n1 = 123
>>>n2 = n1
>>>id(n1),id(n2)
(1485790864, 1485790864)
2.浅拷贝:
>>>import copy
>>>n1 = 123
>>>n2 = copy.copy(n1)
>>>id(n1),id(n2)
>>>(1485790864, 1485790864)
3.深拷贝:
>>>import copy
>>>n1 = 123
>>>n2 = copy.deepcopy(n1)
>>>id(n1),id(n2)
>>>(1485790864, 1485790864)
2. 其他基本数据类型:
对于字典,元组,列表而言,进行赋值,深浅拷贝的时候,其内存地址是不同的
1. 赋值:只是创建一个变量,该变量指向原来的地址
>>>import copy
>>>n1 = {'k1':'w123','k2':123,'k3':['alxe',456]}
>>>n2 = n1
>>>id(n1),id(n2)
(47806480, 47806480)
2.浅拷贝:在内存中只额外拷贝第一层数据
>>>n1 = {'k1':'w123','k2':123,'k3':['alxe',456]}
>>>n2 = copy.copy(n1)
>>>id(n1),id(n2)
(47805184, 47805472)
>>>id(n1[k1]),id(n2[k1])
(48424320, 48424320)
3.深拷贝:在内存中将所有的数据都拷贝一份,最后一层除外(因为python对字符串和数字进行了内部优化)
>>>import copy
>>>n1 = {'k1':'w123','k2':123,'k3':['alxe',456]}
>>>n2 = copy.deepcopy(n1)
>>>id(n1),id(n2)
(47867920, 48790000)
>>>id(n1['k1']),id(n2['k1'])
(48490560, 48490560)
>>>id(n1['k3']),id(n2['k3'])
(47353408, 48495352)