【问题标题】:How to selectively deep-copy in python?如何在 python 中选择性地进行深度复制?
【发布时间】:2019-10-22 00:14:39
【问题描述】:

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

现在我也想做一个 class2 对象的 deepcopy。它还将对 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

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

【问题讨论】:

标签: python python-3.x deep-copy


【解决方案1】:

使用 __deepcopy__ 钩子方法自定义对象的深度复制方式。

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

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 2018-10-08
    • 2018-07-30
    相关资源
    最近更新 更多