假设我有一个l
包含以下内容的python列表:immutables.
当我执行浅表复制和深表复制时,结果是相同的:
>>> 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
这是否意味着浅拷贝和深拷贝仅对mutable
类型的集合有意义,因为immutable
类型永远不会改变。但是,如果我们想为这些类型的集合实现类似行为的深层复制,我们该怎么做?
问候。
由于您不能更改不可变对象,因此在复制时创建相同对象的副本是没有意义的。
根据copy
源代码,像这样完成不可变类型的浅表复制
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
函数在浅表复制期间按原样返回对象。
以同样的方式,在元组的深层复制期间,根据_deepcopy_tuple
函数,按原样返回对象,
d = id(x)
try:
return memo[d]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句