This question already has answers here:
How to override the copy/deepcopy operations for a Python object?

(7 个回答)


3年前关闭。




我有一个对象,它有自己的内容(即某物的列表)和对另一个对象的引用,它与之链接。如何从深度复制中排除对另一个对象的引用?
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 :



只需返回您的类的一个新实例,您不希望被深度复制的引用只是按原样获取。使用 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 - 如何从 deepcopy 中排除特定引用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50352273/

10-12 21:43