如何在 Python 中创建对象的副本? [英] How can I create a copy of an object in Python?

查看:40
本文介绍了如何在 Python 中创建对象的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个对象的副本.我希望新对象拥有旧对象的所有属性(字段的值).但我想拥有独立的对象.所以,如果我改变新对象的字段值,旧对象应该不会受到影响.

I would like to create a copy of an object. I want the new object to possess all properties of the old object (values of the fields). But I want to have independent objects. So, if I change values of the fields of the new object, the old object should not be affected by that.

推荐答案

要获得完全独立的对象副本,您可以使用 copy.deepcopy() 函数.

To get a fully independent copy of an object you can use the copy.deepcopy() function.

有关浅复制和深复制的更多详细信息,请参阅此问题的其他答案以及 相关问题的答案.

For more details about shallow and deep copying please refer to the other answers to this question and the nice explanation in this answer to a related question.

这篇关于如何在 Python 中创建对象的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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