- 直接赋值:其实就是对象的引用(别名)
- 浅拷贝:拷贝父对象,不会拷贝对象内部的子对象
-
深拷贝:
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 -
b=a.copy():浅拷贝, a 和 b 是一个独立的对象,但他们的子对象还是指向统一对象(是引用)
b=a.copy() -
b = copy.deepcopy(a):深度拷贝, a 和 b 完全拷贝了父对象及其子对象,两者是完全独立的。
b=copy.deepcopy(a)
参考:http://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html
网友评论