为什么不可变列表的浅表副本和深表副本之间没有区别 [英] Why there is no difference between shallow copy and deep copy for a list of immutables

查看:79
本文介绍了为什么不可变列表的浅表副本和深表副本之间没有区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个由个不可变对象组成的python列表 l 我在做浅拷贝时深拷贝,结果是相同的:

Suppose i have a python list l consisting of immutables.When i am doing a shallow copy and a deep copy, the result is same:

>>> a = (1,2) # immutable types
>>> b = (3,4)
>>> l = [a,b] # a list containing immutable types

>>> import copy
>>> y = copy.copy(l) # shallow copy
>>> z = copy.deepcopy(l) # deep copy

>>> id(l[0])
139857440375584
>>> id(y[0])
139857440375584
>>> id(z[0])
139857440375584 # all have the same id's , so all refer to the same object

是否表示浅拷贝深拷贝仅对可变类型的集合有意义因为不可变类型永远不会改变。
但是,如果我们想对这类类型的馆藏实现类似的深复制行为,该怎么办呢?

Does it means that shallow copy and deep copy has a meaning only for collections of mutable types because immutable types never changes. But if we want to achieve a deep copy like behavior for the these type of collections how can we do that?

注意

推荐答案

由于您无法更改不可变对象,因此在复制时创建相同对象的副本毫无意义。

Since you cannot change the immutable objects, there is no point in creating copies of the same while copying.

按照 copy 的源代码,不可变类型的浅表复制就是这样

As per copy's source code, shallow copy of immutable types is done like this

def _copy_immutable(x):
    return x

for t in (type(None), int, long, float, bool, str, tuple,
          frozenset, type, xrange, types.ClassType,
          types.BuiltinFunctionType, type(Ellipsis),
          types.FunctionType, weakref.ref):
    d[t] = _copy_immutable

对于所有不可变类型, _copy_immutable 函数返回objec

For all the immutable types, the _copy_immutable function returns the object as it is, during shallow copy.

在元组的深层复制期间,方法相同,则根据 _deepcopy_tuple 函数

The same way, during the deepcopy of tuples, the object is returned as is, as per the _deepcopy_tuple function,

d = id(x)
try:
    return memo[d]

这篇关于为什么不可变列表的浅表副本和深表副本之间没有区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆