理解 Python 2.x 中的深拷贝和浅拷贝 [英] Understanding Deep vs Shallow Copy in Python 2.x

查看:55
本文介绍了理解 Python 2.x 中的深拷贝和浅拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上查找时发现了这 3 段代码.问题是预测输出并解释原因.

I was looking online and I came across these 3 segments of code. The question is to predict the output and explain why.

示例 1:

x = 42
y = x
x = x + 1
print x
print y

输出示例 1:

43
42

示例 2:

x = [1, 2, 3]
y = x
x[0] = 4
print x
print y

输出示例 2:

[4, 2, 3]
[4, 2, 3]

示例 3:

x = ['foo', [1,2,3], 10.4]
y = list(x) # or x[:]
y[0] = 'fooooooo'
y[1][0] = 4
print x
print y

输出示例 3:

['foo', [4, 2, 3], 10.4]
['fooooooo', [4, 2, 3], 10.4]

在大多数情况下,我明白这是一个关于浅拷贝和深拷贝的问题,但我似乎无法理解这个简单的事情.在 x[0] = 4 的示例 2 中,我知道 xy 指向同一个对象,因此 xy 在此语句中被重新定义,而不仅仅是 x.但是为什么在示例 3 中没有遵循相同的逻辑.在 y[0] = 'foooooooo' 这应该导致 xy 被重新定义,就像在 y 处的以下行[1][0] = 4 导致 xy 一起重新定义.

For the most part I understand that this is a question about shallow and deep copying but I can't seem to wrap my head around this simple thing. In Example 2 at x[0] = 4 I understand that x and y are pointing to the same object and therefore both x and y are redefined and not just x in this statement. But then why in Example 3 does this same logic not follow. At y[0] = 'fooooooo' this should cause x and y to be redefined, just like the following line at y[1][0] = 4 causes both x and y to be redefined together.

推荐答案

好的,我们可以再详细分析一下:

Ok so we can dissect this a bit more:

>>> x = ['foo', [1,2,3], 10.4]
>>> y = list(x) # or x[:]
>>> z=x
>>> id(x)
4354889544
>>> id(y)
4354890184
>>> id(z)
4354889544

>>> y[0] = 'fooooooo'
>>> y[1][0] = 4
>>> y
['fooooooo', [4, 2, 3], 10.4]
>>> x
['foo', [4, 2, 3], 10.4]
>>> id(x[1])
4354889672
>>> id(y[1])
4354889672

现在看到了吗?当您使用函数 List() 时,它会在新的内存位置创建一个新对象……但为了节省空间,python 将保留指向可变内部对象(如列表)的相同指针.这篇文章可以解释更多什么是可变的和什么不是.

See it now? When you use the function List() it is creating a new object in a new memory location... but to save space python will keep the same pointer to the mutable internal objects, like the list. This article can explain more what is mutable and what is not.

这篇关于理解 Python 2.x 中的深拷贝和浅拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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