copyreg
— 注册
pickle
支持函数
¶
源代码: Lib/copyreg.py
copyreg
模块提供腌制特定对象时,定义使用函数的方式。
pickle
and
copy
模块使用这些函数,当腌制/拷贝这些对象时。模块提供有关对象构造函数 (不是类) 的配置信息。这种构造函数可以是工厂函数 (或类实例)。
声明
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. See the
dispatch_table
for more details on the interface of
function
.
constructor_ob parameter is a legacy feature and is now ignored, but if passed it must be a callable.
注意,
dispatch_table
attribute of a pickler object or subclass of
pickle.Pickler
can 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...