copyreg
— 注册
pickle
支持函数
¶
源代码: Lib/copyreg.py
The
copyreg
模块提供腌制特定对象时,定义使用函数的方式。
pickle
and
copy
模块使用这些函数,当腌制/拷贝这些对象时。模块提供有关对象构造函数 (不是类) 的配置信息。这种构造函数可以是工厂函数 (或类实例)。
- copyreg. pickle ( type , function , constructor_ob = None ) ¶
-
声明 function should be used as a “reduction” function for objects of type type . function must return either a string or a tuple containing between two and six elements. See the
dispatch_tablefor more details on the interface of function .The constructor_ob parameter is a legacy feature and is now ignored, but if passed it must be a callable.
注意,
dispatch_tableattribute of a pickler object or subclass ofpickle.Picklercan also be used for declaring reduction functions.
范例 ¶
以下范例愿意展示如何注册 pickle 函数及如何使用它:
>>> import copyreg, copy, pickle
>>> class C:
... 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...