python学习笔记七:浅拷贝深拷贝

原理

浅拷贝

import copy
b = copy.copy(a)

demo:

>>> a=[1,['a']]
>>> b=a
>>> c=copy.copy(a)
>>> a
[1, ['a']]
>>> b
[1, ['a']]
>>> c
[1, ['a']]
>>> id(a)
140556196249680
>>> id(b)
140556196249680
>>> id(c)
140556298139120
>>> a[0]=2
>>> a
[2, ['a']]
>>> c
[1, ['a']]
>>>a[1].append('b')
>>>a
[2,['a','b']]
>>>c
[1,['a','b']]

深拷贝

import copy
b = copy.deepcopy(a)

demo:

>>> a=[1,2,['a','b']]
>>> b=copy.deepcopy(a)
>>> a
[1, 2, ['a', 'b']]
>>> b
[1, 2, ['a', 'b']]
>>> id(a)
140556196175952
>>> id(b)
140556196501336
>>> id(a[0])
11961144
>>> id(b[0])
11961144
>>> id(a[2])
140556196424448
>>> id(b[2])
140556196250472
>>> a[0]=3
>>> a[2].append('c')
>>> a
[3, 2, ['a', 'b', 'c']]
>>> b
[1, 2, ['a', 'b']]
原文地址:https://www.cnblogs.com/lurenjiashuo/p/python-note-copy-deepcopy.html