首页 > 代码库 > Python:深浅拷贝

Python:深浅拷贝

导入模块:

>>> import copy

深浅拷贝:

>>> X = copy.copy(Y) #浅拷贝:只拷贝顶级的对象,或者说:父级对象>>> X = copy.deepcopy(Y) #深拷贝:拷贝所有对象,顶级对象及其嵌套对象。或者说:父级对象及其子对象

例:

>>> D = {name:jack,age:20}>>> C1 = copy.copy(D)>>> C2 = copy.deepcopy(D)>>> id(D);id(C1);id(C2)530352085361114453610248>>> D[name] = tom   #改变源>>> D;C1;C2{age: 20, name: tom}{age: 20, name: jack}{age: 20, name: jack}

如果有嵌套:

D = {name:{first:john,last:lee},job:[IT,HR]}>>> C1 =  copy.copy(D)>>> C2 = copy.deepcopy(D)>>> D;C1;C2{job: [IT, HR], name: {first: john, last: lee}}{job: [IT, HR], name: {first: john, last: lee}}{job: [IT, HR], name: {first: john, last: lee}}>>> id(D);id(C1);id(C2)530185685361159253610056>>> >>> D[job][0] = RRRR   #修改其中一个元素>>> D;C1;C2{job: [RRRR, HR], name: {first: john, last: lee}}{job: [RRRR, HR], name: {first: john, last: lee}}{job: [IT, HR], name: {first: john, last: lee}}

#结论:
(1)深浅拷贝都是对源对象的复制,占用不同的内存空间
(2)如果源对象只有一级目录的话,源做任何改动,不影响深浅拷贝对象
(3)如果源对象不止一级目录的话,源做任何改动,都要影响浅拷贝,但不影响深拷贝
(4)序列对象的切片其实是浅拷贝,即只拷贝顶级的对象

Python:深浅拷贝