繁体   English   中英

将对象引用嵌入其他对象,浅层/深层复制python 3+

[英]Embedding Object reference to other objects, shallow/deepcopy python 3+

如V3.7的python文档中所述( https://docs.python.org/3/library/copy.html

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

我试图通过将对一个列表的引用传递给另一个列表来创建如下的复合对象,并且按照我正在阅读的书,新列表L必须存储对X的引用,并且如果X更改L也必须更改。

X = [1, 2, 3] L = ['a', X, 'b']

但是,在对IDLE的测试中,我可以看到L包含对象[1,2,3] ,因此不存储对X的引用,我通过更改X对此进行了测试,但这并不影响L:

>>> X = [1, 2, 3]
>>> L = ['a', X, 'b']
>>> X
[1, 2, 3]
>>> X=[1,2]
>>> L
['a', [1, 2, 3], 'b']
>>> X
[1, 2]

所以我的问题是

在python 3+中对嵌入对象的引用的含义是否已更改。 如果是,那么这是否意味着浅层复制和深层复制不再有区别,这意味着它们都复制了对象的深层副本,如我的测试所示,似乎与文档相反。

>>> L.copy()
['a', [1, 2, 3], 'b']
>>> import copy
>>> copy.deepcopy(L)
['a', [1, 2, 3], 'b']
>>> 

X=[1,2]将名称X重新绑定到对象。 修改原始对象按预期方式工作:

>>> import copy
>>> X=[1,2,3]
>>> L = [1, X, 2]
>>> L
[1, [1, 2, 3], 2]
>>> L_ = copy.copy(L)
>>> L_
[1, [1, 2, 3], 2]
>>> X.append('WOW') # modify here
>>> L, L_
([1, [1, 2, 3, 'WOW'], 2], [1, [1, 2, 3, 'WOW'], 2]) # the change is reflected in both objects

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM