Python入门之深浅拷贝与直接赋值
-
直接赋值:其实就是对象的引用(别名)。
-
浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。
-
深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。
实例:
>>> a = {"name":"chengd","score":[99,100,149]}
>>> a
{'score': [99, 100, 149], 'name': 'chengd'}
#直接赋值,修改a,b同样会被修改
>>> b = a
>>> b
{'score': [99, 100, 149], 'name': 'chengd'}
>>> a["score"].append(99)
>>> a
{'score': [99, 100, 149, 99], 'name': 'chengd'}
>>> b
{'score': [99, 100, 149, 99], 'name': 'chengd'}
#浅拷贝,修改a,b同样会修改
>>> c = a.copy()
>>> c
{'score': [99, 100, 149], 'name': 'chengd'}
>>> a["score"].append(99)
>>> a
{'score': [99, 100, 149, 99], 'name': 'chengd'}
>>> c
{'score': [99, 100, 149, 99], 'name': 'chengd'}
#深拷贝,修改a,b不会被修改
>>> import copy
>>> d = copy.deepcopy(a)
>>> d
{'score': [99, 100, 149], 'name': 'chengd'}
>>> a["score"].append(99)
>>> a
{'score': [99, 100, 149, 99], 'name': 'chengd'}
>>> d
{'score': [99, 100, 149], 'name': 'chengd'}
解析:
1、b = a: 赋值引用,a 和 b 都指向同一个对象。

2、b = a.copy(): 浅拷贝, a 和 b 是一个独立的对象,但他们的子对象还是指向统一对象(是引用)。

b = copy.deepcopy(a): 深度拷贝, a 和 b 完全拷贝了父对象及其子对象,两者是完全独立的。

参考:http://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html

浙公网安备 33010602011771号