python中的深copy和浅copy

bytes

Python bytes/str
bytes 在Python3中作为一种单独的数据类型,不能拼接,不能拼接,不能拼接

>>> '€20'.encode('utf-8')
b'\xe2\x82\xac20'
>>> b'\xe2\x82\xac20'.decode('utf-8')
'€20'

解码

>>> b'\xa420'.decode('windows-1255')
'₪20'

深copy和浅copy
深copy新建一个对象重新分配内存地址,复制对象内容。浅copy不重新分配内存地址,内容指向之前的内存地址。浅copy如果对象中有引用其他的对象,如果对这个子对象进行修改,子对象的内容就会发生更改。

import copy

#这里有子对象
numbers=['1','2','3',['4','5']]
#浅copy
num1=copy.copy(numbers)
#深copy
num2=copy.deepcopy(numbers)

#直接对对象内容进行修改
num1.append('6')

#这里可以看到内容地址发生了偏移,增加了偏移‘6’的地址
print('numbers:',numbers)
print('numbers memory address:',id(numbers))
print('numbers[3] memory address',id(numbers[3]))
print('num1:',num1)
print('num1 memory address:',id(num1))
print('num1[3] memory address',id(num1[3]))


num1[3].append('6')

print('numbers:',numbers)
print('num1:',num1)
print('num2',num2)

输出:
numbers: ['1', '2', '3', ['4', '5']]
numbers memory address: 1556526434888
numbers memory address 1556526434952
num1: ['1', '2', '3', ['4', '5'], '6']
num1 memory address: 1556526454728
num1[3] memory address 1556526434952
numbers: ['1', '2', '3', ['4', '5', '6']]
num1: ['1', '2', '3', ['4', '5', '6'], '6']
num2 ['1', '2', '3', ['4', '5']]
posted @ 2017-12-10 01:14  {Black_Jack}  阅读(12238)  评论(0编辑  收藏  举报