发布于 4年前

Python中深拷贝和浅拷贝之间的区别是什么?

Python中为了提升内存使用效率,将一个变量赋值给另一个变量名时,实际上是引用了同一个变量,也就是说,在计算机的内存里,他们使用的是同一个东西,只是名字不一样而已,而Python中的变量根据值是否可变分为可变(mutable)和不可变(immutable)两种。

In [1]: a_int = 1

In [2]: another_int = a_int

In [3]: id(a_int), id(another_int)
Out[3]: (4377828880, 4377828880)

In [4]: a_dict = {"hello": "world"}

In [5]: another_dict = a_dict

In [6]: id(a_dict), id(another_dict)
Out[6]: (4426474624, 4426474624)

与此同时,也就意味着如果 a_dict 的值发生了变化,another_dict 的值也会跟着变化:

In [7]: a_dict, another_dict
Out[7]: ({'hello': 'world'}, {'hello': 'world'})

In [8]: a_dict["world"] = "hello"

In [9]: a_dict, another_dict
Out[9]: ({'hello': 'world', 'world': 'hello'}, {'hello': 'world', 'world': 'hello'})

而解决方法就是使用 深拷贝:

In [10]: import copy

In [11]: one_more_dict = copy.deepcopy(a_dict)

In [12]: a_dict, one_more_dict
Out[12]: ({'hello': 'world', 'world': 'hello'}, {'hello': 'world', 'world': 'hello'})

In [13]: a_dict["this"] = "that"

In [14]: a_dict, one_more_dict
Out[14]:
({'hello': 'world', 'world': 'hello', 'this': 'that'},
 {'hello': 'world', 'world': 'hello'})
©2020 edoou.com   京ICP备16001874号-3