How to exclude specific references from deepcopy? [duplicate]

狂风中的少年 提交于 2020-07-09 07:39:30

问题


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

回答1:


Your class can implement a __deepcopy__ method to control how it is copied. From the 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.

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


来源:https://stackoverflow.com/questions/50352273/how-to-exclude-specific-references-from-deepcopy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!