由于一些限制,我需要创建一个对象的新副本以及所有属性的新副本以及其属性的属性等等。python:需要一个打破所有共享标识的深层拷贝
现有的deepcopy()是递归的,但是当被复制的树中的多个对象具有相同的起始标识时,它们也具有相同的结束标识(即使它们的结束标识与它们的起始标识不匹配)。
对于以下情况:
class A:
def __init__(self, x):
self.x = x
v = A(1)
o = [v, v]
copy.deepcopy并执行以下操作:
dc_o = copy.deepcopy(o)
assert dc_o[0] is not o[0] # new identity from the original
assert dc_o[0] is dc_o[1] # but maintains identity within the copied tree
assert dc_o[0] == dc_o[1] # ...as well as value
但是,我需要的是:
r_dc_o = recursive_deepcopy(o)
assert r_dc_o[0] is not o[0] # new identity from the original
assert r_dc_o[0] is not r_dc_o[1] # also new identity from elsewhere inside copy
assert r_dc_o[0] == r_dc_o[1] # while maintaining the same value
我怎样才能做到这一点?
即使它们不是相同的列表,等效列表的比较也是相等的。尝试与'is' /'不是'而不是'=='/'!='进行比较。 – Kevin 2015-02-06 17:02:08
'1'和'2'将*总是*是同一个对象;他们被拘留。 'deepcopy'总是递归的;你只是没有以这种方式进行测试。 – 2015-02-06 17:03:06
对不起,我的测试用例是错误的,我正在修复它。 – Nullpoet 2015-02-06 17:08:52