- 直接賦值:其實就是對象的引用(別名)
- 淺拷貝:拷貝父對象募狂,不會拷貝對象內部的子對象
-
深拷貝:
copy
模塊的deepcopy()
方法办素,完全拷貝了父對象及其子對象
- 實例:
# -*- coding: UTF-8 -*-
import copy
a = {1:[1,2,3]}
b = a
c = a.copy()
d = copy.deepcopy(a)
print "a=",a
print "b=a:",b
print "c=a.copy():",c
print "d=a.deepcopy():",d
print
a[1].append(4)
print "a=",a
print "b=a:",b
print "c=a.copy():",c
print "d=a.deepcopy():",d
print
a[2]='xyz'
print "a=",a
print "b=a:",b
print "c=a.copy():",c
print "d=a.deepcopy():",d
print
輸出:
helloworld@LG-virtual-machine:~/code$ python test.py
a= {1: [1, 2, 3]}
b=a: {1: [1, 2, 3]}
c=a.copy(): {1: [1, 2, 3]}
d=a.deepcopy(): {1: [1, 2, 3]}
a= {1: [1, 2, 3, 4]}
b=a: {1: [1, 2, 3, 4]}
c=a.copy(): {1: [1, 2, 3, 4]}
d=a.deepcopy(): {1: [1, 2, 3]}
a= {1: [1, 2, 3, 4], 2: 'xyz'}
b=a: {1: [1, 2, 3, 4], 2: 'xyz'}
c=a.copy(): {1: [1, 2, 3, 4]}
d=a.deepcopy(): {1: [1, 2, 3]}
解析:
-
b = a: 賦值引用,a 和 b 都指向同一個對象
-
b=a.copy():淺拷貝, a 和 b 是一個獨立的對象祸穷,但他們的子對象還是指向統(tǒng)一對象(是引用)
-
b = copy.deepcopy(a):深度拷貝, a 和 b 完全拷貝了父對象及其子對象性穿,兩者是完全獨立的。
參考:http://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html