码迷,mamicode.com
首页 > 其他好文 > 详细

copy 浅拷贝和深拷贝

时间:2018-06-06 18:26:29      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:浅拷贝和深拷贝   copy   bsp   IV   拷贝   数据   running   div   目录   

 1 #直接赋值和 copy 的区别
 2 dic1={name: Tom, age: 18, hobby: running}
 3 dic2=dic1
 4 
 5 print(dic1)
 6 print(dic2)
 7 
 8 #修改数据 age=28
 9 dic1[age]=28
10 
11 print(dic1)
12 print(dic2)
13 # 浅拷贝: 引用对象   dic2只是对dic1的引用。所以当dic1的值改变,dic2也会随着改变
14 
15 
16 dic3={name: Tom, age: 18, hobby: running}
17 
18 dic4=dic3.copy()
19 #浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
20 print(dic3)
21 print(dic4)
22 #修改数据 age=38
23 dic3[age]=38
24 
25 print(dic3)
26 print(dic4)
27 
28 dic5={name: [Tom,Jack], age:[ 18,28], hobby: [running,football]}
29 
30 dic6=dic5.copy()
31 
32 #浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
33 print(dic5)
34 print(dic6)
35 #修改一级目录(父对象),修改数据  [‘running‘,‘football‘]修改为[‘basketball‘]
36 dic5[hobby]=[basketball,]
37 
38 #修改二级目录(子对象),修改数据  Tom 改成 May
39 dic5[name][0]=May
40 dic5[age][0]=38
41 
42 print(dic5)
43 print(dic6)

结果:

{name: Tom, age: 18, hobby: running}
{name: Tom, age: 18, hobby: running}

{name: Tom, age: 28, hobby: running}
{name: Tom, age: 28, hobby: running}

{name: Tom, age: 18, hobby: running}
{name: Tom, age: 18, hobby: running}

{name: Tom, age: 38, hobby: running}
{name: Tom, age: 18, hobby: running}

{name: [Tom, Jack], age: [18, 28], hobby: [running, football]}
{name: [Tom, Jack], age: [18, 28], hobby: [running, football]}

{name: [May, Jack], age: [38, 28], hobby: [basketball]}
{name: [May, Jack], age: [38, 28], hobby: [running, football]}

 

copy 浅拷贝和深拷贝

标签:浅拷贝和深拷贝   copy   bsp   IV   拷贝   数据   running   div   目录   

原文地址:https://www.cnblogs.com/Mengchangxin/p/9146057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!