python中的深copy和淺copy

bytes

Python bytes/str
bytes 在Python3中做爲一種單獨的數據類型,不能拼接,不能拼接,不能拼接python

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

解碼windows

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

深copy和淺copy
深copy新建一個對象從新分配內存地址,複製對象內容。淺copy不從新分配內存地址,內容指向以前的內存地址。淺copy若是對象中有引用其餘的對象,若是對這個子對象進行修改,子對象的內容就會發生更改。app

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']]
相關文章
相關標籤/搜索