我有多个python类。其中一个类(例如,class1)的对象中包含大量数据(在运行时不会更改)。另一个类(例如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
请帮助我...
在此先感谢
答案 0 :(得分:2)
使用__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