Python深拷贝未复制对象新实例中的字典

0 投票
1 回答
537 浏览
提问于 2025-04-18 03:49

我想复制一个对象,这个对象里面有一个字典。我打算在一个递归树中传递这个对象,希望树中的每个节点都能收到一个新的副本,而不是指向同一个副本。

我发现“new_t1”和“new_t2”这两个对象里面的字典是一样的,尽管它们的对象ID不同。

有没有简单的方法可以真正深度复制一个对象,还是说我必须自己写代码来避免只是把指针指向同一个字典呢?

hcPartial是一个包含字典和其他一些东西的类:

class hc:

    dictionary = {'00':[], '01':[], '10':[], '11':[]}

下面的代码展示了失败的情况:

#Check making two hypercube copies and independently adding to one of them
nhc1 = copy.deepcopy(hcPartial)
nhc2 = copy.deepcopy(hcPartial)

print "ID 1: ", id(nhc1), "ID 2: ", id(nhc2)
print "D ID 1: ", id(nhc1.dictionary), "D ID 2: ", id(nhc2.dictionary)
print nhc1.dictionary
nhc1.forwardConnect('00','01')
print nhc1.dictionary
print nhc2.dictionary
print nhc1
print nhc2

输出结果:

ID 1:  92748416 ID 2:  92748696
D ID 1:  92659408 D ID 2:  92659408
{'11': [], '10': [], '00': [], '01': []}
{'11': [], '10': [], '00': ['01'], '01': []}
{'11': [], '10': [], '00': ['01'], '01': []}
<hypercube.HyperCube2D instance at 0x05873A80>
<hypercube.HyperCube2D instance at 0x05873B98>

预期的输出结果:

{'11': [], '10': [], '00': [], '01': []}
{'11': [], '10': [], '00': ['01'], '01': []}
{'11': [], '10': [], '00': [], '01': []}

修正后的输出结果在类中添加了__init__(),现在可以正常工作了!

ID 1:  92746056 ID 2:  92730952
Dict ID 1:  92665728 Dict ID 2:  92680240
{'11': [], '10': [], '00': [], '01': []}
forwardConnect ID 1:  91704656 forwardConnect ID 2:  91704656
{'11': [], '10': [], '00': ['01'], '01': []}
{'11': [], '10': [], '00': [], '01': []}
<hypercube.HyperCube2D instance at 0x05873148>
<hypercube.HyperCube2D instance at 0x0586F648>

1 个回答

1

如上所述:

问题是我的类里面没有一个

__init__() 

如果你想让每个实例都有自己的字典,你应该把它的初始化从类的层面移到一个方法里:

 __init__(): 
 self.dictionary = ... 

参考资料

撰写回答