gpt4 book ai didi

python - 如何从深层复制中排除特定引用?

转载 作者:行者123 更新时间:2023-12-01 01:54:42 24 4
gpt4 key购买 nike

我有一个对象,它有自己的内容(即某物的列表)和对另一个对象的引用,该对象与其链接。如何排除对其他对象的引用进行深度复制?

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 module documentation :

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 the deepcopy() function with the component as first argument and the memo dictionary as second argument.

只需返回您的类的一个新实例,以及您不想进行深度复制的引用,只需按原样获取即可。使用deepcopy()函数复制其他对象:

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)

演示:

>>> 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

关于python - 如何从深层复制中排除特定引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50352273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com