在以下示例中,我希望Deepcopy可以创建字段的副本,而不仅仅是复制引用。这里发生了什么,有什么简单的方法可以解决?
from copy import deepcopy class Test: field = [(1,2)] t1 = Test() t2 = deepcopy(t1) t2.field[0]=(5,10) print t1.field # [(1,2)] expected but [(5,10)] obtained print t2.field # [(5,10)] expected
输出:
[(5, 10)] [(5, 10)]
深层复制(默认情况下)仅适用于实例级别的属性-不适用于类级别-唯一的多个含义并没有多大意义class.attribute…
class.attribute
将您的代码更改为:
class Test: def __init__(self): self.field = [(1,2)]