python 深copy_python中的深copy和浅copy
bytes
Python bytes/str
bytes 在Python3中作為一種單獨(dú)的數(shù)據(jù)類型,不能拼接,不能拼接,不能拼接
>>> '€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新建一個(gè)對(duì)象重新分配內(nèi)存地址,復(fù)制對(duì)象內(nèi)容。淺copy不重新分配內(nèi)存地址,內(nèi)容指向之前的內(nèi)存地址。淺copy如果對(duì)象中有引用其他的對(duì)象,如果對(duì)這個(gè)子對(duì)象進(jìn)行修改,子對(duì)象的內(nèi)容就會(huì)發(fā)生更改。
import copy
#這里有子對(duì)象
numbers=['1','2','3',['4','5']]
#淺copy
num1=copy.copy(numbers)
#深copy
num2=copy.deepcopy(numbers)
#直接對(duì)對(duì)象內(nèi)容進(jìn)行修改
num1.append('6')
#這里可以看到內(nèi)容地址發(fā)生了偏移,增加了偏移‘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']]
總結(jié)
以上是生活随笔為你收集整理的python 深copy_python中的深copy和浅copy的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信用卡贷款钱到哪里取 转到借记卡中自由支
- 下一篇: python tabula 使用方法_P