8.17。 copy - 浅层和深层复制操作

Python中的赋值语句不会复制对象,它们会在目标和对象之间创建绑定。对于可变的或包含可变项目的集合,有时需要一个副本,因此可以更改一个副本而不改变另一个副本。该模块提供通用的浅层和深层复制操作(如下所述)。

接口总结:

copy.copy(x)

返回x的浅层副本。

copy.deepcopy(x)

返回x的深层副本。

exception copy.error

引起模块特定错误。

浅层和深层复制之间的区别仅适用于复合对象(包含其他对象的对象,如列表或类实例):

  • 浅拷贝构造一个新的复合对象,然后(尽可能地)将引用插入到原始文件中找到的对象。
  • 深拷贝构造一个新的复合对象,然后递归地将副本插入到原始文件中的对象中。

通常在浅拷贝操作中不存在深层复制操作存在两个问题:

  • 递归对象(直接或间接包含对其自身的引用的复合对象)可能会导致递归循环。
  • 因为深层副本复制所有它可能会复制太多,例如甚至在副本之间应共享的管理数据结构。

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

Module pickle
Discussion of the special methods used to support object state retrieval and restoration.

Previous topic

8.16. new — Creation of runtime internal objects

Next topic

8.18. pprint — Data pretty printer

This Page