簡介:
copy模塊主要用於複製對象,有淺copy和深copy之分。
首先得清楚的理解《對象》的概念
對象:
python萬物皆是對象。
對象分爲可變和不可變2類,可變對象如:list,dict等;不可變對象如:基礎類型,元組等。
對象有三大特性分別爲:身份(id(a)),類型(type(a)),值(a)。
淺copy:
對象是不可變對象時:拷貝對象和原對象的三大特性一致
對象是可變對象時:拷貝對象和原對象的三大特性一致
深copy:
對象是不可變對象時:拷貝對象和原對象的三大特性一致
對象是可變對象時:拷貝的對象和原對象的類型和值一致,身份不一致
具體如下:
淺copy
import copy
x = 1
y = [11]
a = [x, y]
b = copy.copy(a)
print 'a[0] = %s and b[0] = %s' % (a[0], b[0])
print 'type(a[0]) = %s and type(b[0]) = %s' % (type(a[0]),type(b[0]))
print 'id(a[0]) = %s and id(b[0]) = %s' % (id(a[0]),id(b[0]))
print '*********************'
print 'a[1] = %s and b[1] = %s' % (a[1], b[1])
print 'type(a[1]) = %s and type(b[1]) = %s' %(type(a[1]), type(b[1]))
print 'id(a[1]) = %s and id(b[1]) = %s' % (id(a[1]),id(b[1]))
結果:
a[0] = 1 and b[0] = 1
type(a[0]) = <type 'int'> and type(b[0]) = <type 'int'>
id(a[0]) = 31817608 and id(b[0]) = 31817608
*********************
a[1] = [11] and b[1] = [11]
type(a[1]) = <type 'list'> and type(b[1]) = <type 'list'>
id(a[1]) = 36362440 and id(b[1]) = 36362440
通過結果發現,a和b的三大特性完全一致。
深copy
import copy
x = 1
y = [11]
a = [x, y]
b = copy.deepcopy(a)
print 'a[0] = %s and b[0] = %s' % (a[0], b[0])
print 'type(a[0]) = %s and type(b[0]) = %s' %(type(a[0]), type(b[0]))
print 'id(a[0]) = %s and id(b[0]) = %s' % (id(a[0]),id(b[0]))
print '*********************'
print 'a[1] = %s and b[1] = %s' % (a[1], b[1])
print 'type(a[1]) = %s and type(b[1]) = %s' %(type(a[1]), type(b[1]))
print 'id(a[1]) = %s and id(b[1]) = %s' % (id(a[1]),id(b[1]))
結果:
a[0] = 1 and b[0] = 1
type(a[0]) = <type 'int'> and type(b[0]) = <type 'int'>
id(a[0]) = 31555464 and id(b[0]) = 31555464
*********************
a[1] = [11] and b[1] = [11]
type(a[1]) = <type 'list'> and type(b[1]) = <type 'list'>
id(a[1]) = 36624584 and id(b[1]) = 36635656
通過結果發現,a[0]和b[0]的三大特性完全一致,a[1]和b[1]的類型和值一致,身份不一致。