Python:Deepcopy在用户定义的类上不起作用? [英] Python: deepcopy does not work on user-defined classes?

查看:160
本文介绍了Python:Deepcopy在用户定义的类上不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中,我希望Deepcopy可以创建字段的副本,而不仅仅是复制引用。

In the following example I would expect deepcopy to create a copy of field and not just copy the reference. What happens here and is there an easy way around it?

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)]


推荐答案

深度复制(默认情况下)仅适用于实例级别的属性-不适用于类级别-唯一的<$ c $个以上并没有多大意义c> class.attribute ...

Deep copying (by default) only applies to instance level attributes - not class level - It doesn't make much sense that there's more than one unique class.attribute...

将代码更改为:

class Test:
    def __init__(self):
        self.field = [(1,2)]

这篇关于Python:Deepcopy在用户定义的类上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆