Python中的赋值语句不会复制对象,它们会在目标和对象之间创建绑定。对于可变的或包含可变项目的集合,有时需要一个副本,因此可以更改一个副本而不改变另一个副本。该模块提供通用的浅层和深层复制操作(如下所述)。
接口总结:
返回x的浅层副本。
返回x的深层副本。
引起模块特定错误。
浅层和深层复制之间的区别仅适用于复合对象(包含其他对象的对象,如列表或类实例):
通常在浅拷贝操作中不存在深层复制操作存在两个问题:
deepcopy()功能通过以下方式避免了这些问题:
该模块不会复制模块,方法,堆栈跟踪,堆栈框架,文件,套接字,窗口,数组或类似类型的类型。它通过返回原始对象不变“复制”功能和类(浅和深)这与pickle模块处理的方式兼容。
可以使用dict.copy()和列表通过分配整个列表的片段,例如copied_list = original_list [:]。
Changed in version 2.5: Added copying functions.
类可以使用相同的界面来控制它们用于控制酸洗的复制。See the description of module pickle for information on these methods. The copy module does not use the copy_reg registration module.
In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument.
See also