copy_reg
— 注册
pickle
支持函数
¶
注意
The
copy_reg
module has been renamed to
copyreg
in Python 3. The
2to3
tool will automatically adapt imports when converting your sources to Python 3.
The
copy_reg
模块提供腌制特定对象时,定义使用函数的方式。
pickle
,
cPickle
,和
copy
模块使用这些函数,当腌制/拷贝这些对象时。模块提供有关对象构造函数 (不是类) 的配置信息。这种构造函数可以是工厂函数 (或类实例)。
copy_reg.
pickle
(
type
,
function
[
,
构造函数
]
)
¶
声明
function
should be used as a “reduction” function for objects of type
type
;
type
must not be a “classic” class object. (Classic classes are handled differently; see the documentation for the
pickle
module for details.)
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
构造函数
不可调用。
见
pickle
module for more details on the interface expected of
function
and
构造函数
.
以下范例愿意展示如何注册 pickle 函数及如何使用它:
>>> import copy_reg, 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,)
...
>>> copy_reg.pickle(C, pickle_c)
>>> c = C(1)
>>> d = copy.copy(c)
pickling a C instance...
>>> p = pickle.dumps(c)
pickling a C instance...