我想复制一个对象(包含一个字典)。我计划在递归树中传递这个对象,我希望树中的每个节点都接收一个新的副本,而不是一个链接的副本。
我发现对象"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>发布于 2016-11-07 23:18:04
如上所述:
问题被证明是我的类没有
__init__() 在里面。
如果您希望每个实例都有自己的字典,则应该将其初始化从类级别移动到方法中:
__init__():
self.dictionary = ... 参考
https://stackoverflow.com/questions/23231490
复制相似问题