python之copy,deepcopy

赋值

# c与a指向同一对象
In [71]: a = [0, [1, 2], 3]


In [75]: c = a

In [76]: id(c)
Out[76]: 140506513737928

In [77]: id(a)
Out[77]: 140506513737928

浅拷贝

# 只拷贝对象的引用
In [71]: a = [0, [1, 2], 3]

In [72]: b = a[:]

In [73]: id(a)
Out[73]: 140506513737928

In [74]: id(b)
Out[74]: 140506514004104

In [78]: b[1].append(3)

In [79]: b
Out[79]: [0, [1, 2, 3], 3]

In [80]: a
Out[80]: [0, [1, 2, 3], 3]

图片来源于网络

深拷贝

# 复制真实的对象
In [81]: import copy

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

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

In [84]: b
Out[84]: [0, [1, 2], 3]

In [85]: id(b[1])
Out[85]: 140506534178056

In [86]: id(a[1])
Out[86]: 140506522688136

In [87]: b[1].append(3)

In [88]: b
Out[88]: [0, [1, 2, 3], 3]

In [89]: a
Out[89]: [0, [1, 2], 3]

图片来源于网络


浅拷贝和深拷贝的不同之处是对于可变对象来说的,因为对于不可变对象复制对象的引用和复制对象是一样的(因为当要改变值时,会重新创建个对象)。当使用浅拷贝时,对于嵌套的列表只会拷贝其引用,而深拷贝则会复制真实的对象。切片也属于浅拷贝。


Ref:
1.https://my.oschina.net/leejun2005/blog/145911