对象引用
>>> a = [1,2,3,4]
>>> b = a
>>> b is a
True
>>> b[2] = -100
>>> b
[1, 2, -100, 4]
>>> a
[1, 2, -100, 4]
a
和b
引用的是同一个对象,修改其中的一个将影响另一个。
对于像列表和字典这样的容器对象,可以使用浅复制和深复制。
浅复制
浅复制可以创建一个新对象,包含的是对原始对象中包含的项的引用:
>>> a = [1, 2, [3, 4]]
>>> b = list(a)
>>> b is a
False
>>> b.append(100)
>>> b
[1, 2, [3, 4], 100]
>>> a
[1, 2, [3, 4]]
>>> b[2][0] = -100
>>> b
[1, 2, [-100, 4], 100]
>>> a
[1, 2, [-100, 4]]
深复制
>>> import copy
>>> a = [1,2,[3,4]]
>>> b = copy.deepcopy(a)
>>> a
[1, 2, [3, 4]]
>>> b
[1, 2, [3, 4]]
>>> a[1] = 7
>>> a
[1, 7, [3, 4]]
>>> b
[1, 2, [3, 4]]