python中浅拷贝和深拷贝的区别_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'})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值