如何从Deepcopy中排除特定引用? [英] How to exclude specific references from deepcopy?
问题描述
我有一个对象,该对象具有自己的内容(即某物的列表),并且具有与另一个对象相关联的引用。如何从深度复制中排除对另一个对象的引用?
I have object which has it's own content (i.e. list of something) and a reference to another object, with which it is linked. How can I exclude the reference to the other object from being deep-copied?
from copy import deepcopy
class Foo:
def __init__(self, content, linked_to):
self.content = content
self.linked_to = linked_to
a1 = Foo([[1,2],[3,4]], None)
a2 = Foo([[5,6],[7,8]], a1)
a3 = deepcopy(a2) # <- I don't want there, that a3.linked_to will be copied
# I want that a3.linked_to will still point to a1
a3.linked_to.content.append([9,10])
print a1.content # [[1,2],[3,4]], but I want [[1,2],[3,4], [9,10]]
推荐答案
您的类可以实现 __deepcopy __
方法来控制其复制方式。来自 copy
模块文档:
Your class can implement a __deepcopy__
method to control how it is copied. From the copy
module documentation:
为了让一个类定义自己的副本实现,它可以定义特殊方法
__ copy __( )
和__ deepcopy __()
。前者被称为实现浅拷贝操作;没有传递其他参数。后者被称为实现深度复制操作。它传递了一个参数,即备忘字典。如果__ deepcopy __()
实现需要对组件进行深拷贝,则应调用deepcopy()
函数
In order for a class to define its own copy implementation, it can define special methods
__copy__()
and__deepcopy__()
. The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the__deepcopy__()
implementation needs to make a deep copy of a component, it should call thedeepcopy()
function with the component as first argument and the memo dictionary as second argument.
简单地返回类的新实例,并带有引用不想被复制原样。使用 deepcopy()
函数复制其他对象:
Simply return a new instance of your class, with the reference you don't want to be deep-copied just taken across as-is. Use the deepcopy()
function to copy other objects:
from copy import deepcopy
class Foo:
def __init__(self, content, linked_to):
self.content = content
self.linked_to = linked_to
def __deepcopy__(self, memo):
# create a copy with self.linked_to *not copied*, just referenced.
return Foo(deepcopy(self.content, memo), self.linked_to)
Demo :
>>> a1 = Foo([[1, 2], [3, 4]], None)
>>> a2 = Foo([[5, 6], [7, 8]], a1)
>>> a3 = deepcopy(a2)
>>> a3.linked_to.content.append([9, 10]) # still linked to a1
>>> a1.content
[[1, 2], [3, 4], [9, 10]]
>>> a1 is a3.linked_to
True
>>> a2.content is a3.content # content is no longer shared
False
这篇关于如何从Deepcopy中排除特定引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!