首页 > 解决方案 > 可视化深拷贝和浅拷贝之间的差异

问题描述

我明白深拷贝和浅拷贝有什么区别。

深拷贝将一个对象复制到另一个对象中。这意味着如果您对对象的副本进行更改,它不会影响原始对象。在 Python 中,我们为此使用函数 deepcopy(),并导入模块副本。我们像这样使用它:

为了可视化它,我使用了 python 导师并得到了这个,

import copy
a = [1, 2, 3]

b = copy.deepcopy(a)

在此处输入图像描述

这是有道理的,因为它在我使用deepcopy()函数时创建了一个新对象。

另一方面,浅拷贝是,

然而,浅拷贝将一个对象的引用复制到另一个对象。因此,如果我们在副本中进行更改,它将影响原始对象。为此,我们有函数 copy()。

但是当我使用浅拷贝时,为什么会得到相同的结果?

import copy
a = [1, 2, 3]

b = copy.deepcopy(a)
c = copy.copy(a)

在此处输入图像描述

据我了解,浅拷贝应该引用同一个对象(即a,而不是创建一个新对象如下,

c = a

在此处输入图像描述

有人可以告诉我为什么deepcopy()浅拷贝和浅拷贝都创建一个新对象吗?

标签: python

解决方案


copy makes a copy of the parent object only. It makes a new object that points to all the same attributes as the original object. deepcopy - 1) copies the original object, 2) then runs copy on each attribute pointed to, then makes copies of any attributes that those other copies point to etc....

In your case, since the attributes of your list are immutable, copy and deepcopy are interchangeable. if you have a list of lists, or list of lists of lists or ... then you use deepcopy.

Here is a quick example of the difference:

>>> example = [[1, 2, 3], [4, 5, 6]]
>>> same_obj = example
>>> shallow_copy = copy(example)
>>> deep_copy = deepcopy(example)
>>> example.append([7, 8, 9])
>>> print(example)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(same_obj)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(shallow_copy)
[[1, 2, 3], [4, 5, 6]]
>>> example[0].sort(reverse=True)
>>> print(example)
[[3, 2, 1], [4, 5, 6], [7, 8, 9]]
>>> print(shallow_copy)
[[3, 2, 1], [4, 5, 6]]
>>> print(deep_copy)
[[1, 2, 3], [4, 5, 6]]

shallow_copy and example are two different objects. They have indexes which point to other objects (in this case, lists). These indexes are all pointing to the same objects, so if you mutate the object that either list points to, the mutation shows up in both lists. deepcopy, not only copied the parent list, but also copied each list that the parent list pointed to. so any changes to a sub-list did not affect deep_copy in any way.


推荐阅读