如何在 python 中有选择地进行深度复制?

How to selectively deep-copy in python?

我有多个 python class。 classes 之一的对象(例如,class1)中包含大量数据(在运行时不会更改)。另一个 class(比如 class2)有一个映射到 class1 的对象之一的成员变量。假设 class1 和 class2 有其他可变和不可变成员变量。

现在我也想对 class2 的对象进行深层复制。它还将对 class2 中的 class1 对象进行深层复制。但为了节省内存,我想避免这种情况。我该怎么做呢?

class class1:
    def __init__(self):
        self.largeData = None
        self.mutableVar = None
        self.immutableVar = None


class class2:
    def __init__(self, objc1: class1):
        self.objc1 = objc1  # of the type class1
        self.mutableVar = None
        self.immutableVar = None


c1_1 = class1()
c1_2 = class1()

c2_1 = class2(c1_1)

c2_1Copy = copy.deepcopy(c2_1)
# i want c2_1Copy to reference the same objc1 as c2_1,
# but different mutablevar and immutablevar

c2_2 = class2(c1_2)  # Note: cannot use static variable

请帮我解决这个问题...
提前致谢

使用 __deepcopy__ 挂钩方法自定义您的对象 deep-copied。

import copy


class LargeDataContainer:
    def __init__(self):
        self.data = "x" * 800


class Thing:
    def __init__(self, large_data: LargeDataContainer):
        self.large_data = large_data
        self.x = [1, 2, 3]

    def __deepcopy__(self, memo):
        new_inst = type(self).__new__(self.__class__)  # skips calling __init__
        new_inst.large_data = self.large_data  # just assign

        # rinse and repeat this for other attrs that need to be deepcopied:
        new_inst.x = copy.deepcopy(self.x, memo)
        return new_inst


ldc = LargeDataContainer()

t1 = Thing(ldc)
t2 = copy.deepcopy(t1)
assert t1 is not t2
assert t1.large_data is t2.large_data
assert t1.x is not t2.x