深度复制是否使用写时复制?
我想知道 python 解释器在对可变对象进行深度复制时是否应用写时复制策略。
另外,我想知道深度复制是否也在不可变对象上执行(但这对我来说似乎很奇怪)
I wonder if the python interpreter applies copy on write strategy when doing a deepcopy on mutable objects.
Also, I'd like to know if the deepcopy is performed also on nonmutable object (that would seem strange to me however)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不进行写时复制。
它不会对某些内置不可变类型进行深层复制,但任何用户定义的“不可变”类型都将被深层复制。
Python 2.7 标准库中的 copy.py 包含此消息它的文档:
copy
像这样处理不可变对象:deepcopy
使用更复杂的方案,它太长而无法复制到其中,但要点是相同的。一个有趣的点是_deepcopy_tuple
会迭代其元素,并且在找到被复制的元素之前不会创建新对象。It does not do copy-on-write.
It doesn't do a deep copy on some built-in immutable types, but any user-defined "immutable" types will be deep-copied.
copy.py in the Python 2.7 standard library includes this message in its documentation:
copy
handles immutable objects like this:deepcopy
uses a more complicated scheme that's too long to copy into this most, but the gist is the same. One interesting point is that_deepcopy_tuple
iterates through its elements and don't create a new object until it finds an element that was copied.不,不是的,只是复制对象。如果不可变对象引用可变对象,它也必须复制它们。
No, it doesn't it, just copies the objects. And it also must copy immutable objects if they reference mutables.
让我们看看:
对于
x
和y
的第一个元素,执行了复制,对象有了新的id。第三个元素是一个不可变的字符串,不会被复制。Let's see:
For the first element of
x
andy
, the copy is performed and the object has a new id. The third element, an immutable string, is not copied.