12.2. copyreg — 注册 pickle 支持函数

源代码: Lib/copyreg.py


copyreg 模块提供腌制特定对象时,定义使用函数的方式。 pickle and copy 模块使用这些函数,当腌制/拷贝这些对象时。模块提供有关对象构造函数 (不是类) 的配置信息。这种构造函数可以是工厂函数 (或类实例)。

copyreg. 构造函数 ( object )

声明 object 成为有效构造函数。若 object 不可调用 (因此作为构造函数无效),引发 TypeError .

copyreg. pickle ( type , function , constructor=None )

声明 function should be used as a “reduction” function for objects of type type . function should return either a string or a tuple containing two or three elements.

可选 构造函数 parameter, if provided, is a callable object which can be used to reconstruct the object when called with the tuple of arguments returned by function at pickling time. TypeError 会被引发若 object is a class or 构造函数 is not callable.

pickle module for more details on the interface expected of function and 构造函数 。注意, dispatch_table attribute of a pickler object or subclass of pickle.Pickler can also be used for declaring reduction functions.

12.2.1. 范例

以下范例愿意展示如何注册 pickle 函数及如何使用它:

>>> import copyreg, copy, pickle
>>> class C(object):
...     def __init__(self, a):
...         self.a = a
...
>>> def pickle_c(c):
...     print("pickling a C instance...")
...     return C, (c.a,)
...
>>> copyreg.pickle(C, pickle_c)
>>> c = C(1)
>>> d = copy.copy(c)
pickling a C instance...
>>> p = pickle.dumps(c)
pickling a C instance...