【问题标题】:Python's Deep copy doesn't make copy of dictionary inside new instances of objectsPython 的深层副本不会在对象的新实例中复制字典
【发布时间】:2014-04-22 22:33:24
【问题描述】:

我想复制一个对象(包含字典)。我计划在递归树中传递这个对象,我希望树中的每个节点都接收一个新副本,而不是链接副本。

我发现对象“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>

【问题讨论】:

  • hcPartial是什么类?
  • 它包含一个字典,编辑:普通python字典。
  • 你的意思是字典,还是包含字典的类?这是一个重要的区别。我问是因为字典没有forwardConnect 方法。
  • 啊,我明白了。它包含一个字典。 forwardConnect(a,b) 与 dict[a] = b 相同,只是增加了一些关于 a 和 b 可以是什么的合法性检查。我只是尝试了一个普通的 dict[a] = b,它有复制到两个字典的相同问题。这并不奇怪,因为它们具有相同的 ID。我想我会写一个函数来按值复制字典值。如果有人有更好的主意,请告诉我:D
  • dictionary 在您的代码中被定义为一个类属性,即,该类的 所有 个实例共享它。如果您希望每个实例都有自己的字典,则应将其初始化从类级别移至方法中,例如 __init__(): self.dictionary = ...

标签: python copy deep-copy


【解决方案1】:

如上所述:

问题原来是我的班级没有

__init__() 

在里面。

如果您希望每个实例都有自己的字典,您应该将其初始化从类级别移到方法中:

 __init__(): 
 self.dictionary = ... 

参考文献

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2016-03-28
    • 2015-12-28
    • 2019-04-08
    • 1970-01-01
    相关资源
    最近更新 更多