2018-07-23 对象的复制与引用

1. 列表(list)

alist = [1, 2, 3]  ## 初始化一个列表
blist = alist   ## blist 引用 akist
clist = alist[:]  ## clist 复制 alist
print("old list is :")
print "alist is : ", alist
print "blist is : ", blist
print "clist is : ", clist
alist[1] = 3
print("new list is :")
print "alist is : ", alist
print "blist is : ", blist
print "clist is : ", clist

结果如下所示:

(python_test) ➜  20180723 python test.py
old list is :
alist is :  [1, 2, 3]
blist is :  [1, 2, 3]
clist is :  [1, 2, 3]
new list is :
alist is :  [1, 3, 3]
blist is :  [1, 3, 3]
clist is :  [1, 2, 3]
(python_test) ➜  20180723 

其变量与对象的变化如下图所示


2018-07-23 对象的复制与引用_第1张图片
list的对象与列表的关系

2. 字典(dict)

adict = {'name': 'zhaoxin'}
bdict = adict
cdict = adict.copy()
print("old dict is: ")
print "adict is : ", adict
print "bdict is : ", bdict
print "cdict is : ", cdict
adict['name'] = 'songzhen'
print("new dict is: ")
print "adict is : ", adict
print "bdict is : ", bdict
print "cdict is : ", cdict

结果如下所示:

(python_test) ➜  20180723 python test2.py 
old dict is: 
adict is :  {'name': 'zhaoxin'}
bdict is :  {'name': 'zhaoxin'}
cdict is :  {'name': 'zhaoxin'}
new dict is: 
adict is :  {'name': 'songzhen'}
bdict is :  {'name': 'songzhen'}
cdict is :  {'name': 'zhaoxin'}
(python_test) ➜  20180723 

3. 深度复制

无条件值的分片和字典的copy只能做顶层复制,如果需要一个深层嵌套的数据结构的完整的,完全独立的复制,则需要使用标准的copy模块来处理。

如下例所示:

import copy
dict1 = {"name": 'zhaoxin'}
test1 = [1, 2, 3, [3, 4, dict1]]
test2 = test1[:]    ## 顶层复制
test3 = copy.deepcopy(test1)  ## 深度复制
print "old is : "
print "test1 is : ", test1
print "test2 is : ", test2
print "test3 is : ", test3

dict1["name"] = "songzhen"
test1[2] = 4
print "new is : "
print "test1 is : ", test1
print "test2 is : ", test2
print "test3 is : ", test3

结果如下所示

(python_test) ➜  20180723 python test3.py
old is : 
test1 is :  [1, 2, 3, [3, 4, {'name': 'zhaoxin'}]]
test2 is :  [1, 2, 3, [3, 4, {'name': 'zhaoxin'}]]
test3 is :  [1, 2, 3, [3, 4, {'name': 'zhaoxin'}]]
new is : 
test1 is :  [1, 2, 4, [3, 4, {'name': 'songzhen'}]]
test2 is :  [1, 2, 3, [3, 4, {'name': 'songzhen'}]]
test3 is :  [1, 2, 3, [3, 4, {'name': 'zhaoxin'}]]
(python_test) ➜  20180723 

你可能感兴趣的:(2018-07-23 对象的复制与引用)