Python高级第二周

2018-08-19  本文已影响0人  卑微小利

1,浅拷贝
^浅拷贝是对一个对象的顶层拷贝
^通俗的理解就是:拷贝了引用,并没有拷贝内容

In [2]: a = [11,22,33,44]

In [3]: id(a)
Out[3]:140654480911944

In [4]: b = a

In [5]: id(b)
Out [5]: 140654480911944

In [6]: a.append(55)

In [7]: a
Out[7]: [11,22,33,44,55]

In [8]: b
Out[8]: [11,22,33,44,55]

In [9]: a = {'name':'张杰'}

In [10]:id(a)
Out[10]:140654496320392

In [11]: b = a

In [12]: id(b)
Out[12]: 140654496320392

In [13]: a['ID'] = 100

In [10]: id(a)
Out[10]: 140654496320392

In [11]: b = a

In [12]: id(b)
Out[12]:  140654496320392

In [13]: a['ID'] = 100

In [14]: a
Out[14]: {'ID':100,'name':'张杰'}

In [15]: b
Out[15]: {'ID':100,'name':'张杰'}

In [16]: id(a)
Out[16]:  140654496320392

In[17]: id(b)
Out[17]: 140654496320392

2,深拷贝
^深拷贝是对于一个对象所有层次的拷贝(递归)

In [2]: import copy

In [3]: a = [1,2,3]

In[4]: id(a)
Out[4]: 139884679267656

In [5]: b = copy.deepcopy(a)

In[6]: id(b)
Out[6]: 139884679237704

In[7]: a
Out[7]: [1,2,3]

In [8]: b
Out[8]: [1,2,3]

In [9]:
In [2]: import copy

In[3]: a = [1,2,3]

In [4]: id(a)
Out[4]: 139884679267656

In [5]: b = copy.deepcopy(a)

In [6]: id(b)
Out[6]: 139884679237704

In [7]: a
Out[7]: [1,2,3]

In [8]: b 
Out[8]: [1,2,3]

In [9]: a.append(4)

In [10]: a
Out[10]: [1,2,3,4]

In [11]: b
Out[11]: [1,2,3]

……进一步理解拷贝

In [2]: a = [1,2,3]

In [3]: b = [4,5,6]

In [4]: c = [a,b]

In [5]: d = c

In [6]: id(c)
Out[6]: 140558307928200

In [7]: id(d)
Out[7]: 140558307928200

In [8]: e = copy.deepcopy(c)
……………………………………………………………………
In [9]: import copy
copy      copyreg
In [9]: import copy

In[10]:  e = copy.deepcopy(c)

In[11]: id(e)
Out[11]: 140558286377288

In [13]: a
Out[13]: [1,2,3,4]

In[14]: b
Out[14]: [4,5,6]

In [15]: c
Out[15]: [[1,2,3,4],[4,5,6]]

In [16]: e
Out[16]: [[1,2,3],[4,5,6]]

In [17]: d
Out[17]:[[1,2,3,4],[4,5,6]]
上一篇 下一篇

猜你喜欢

热点阅读