copyreg --- 注册配合 pickle 模块使用的函数¶
源代码: Lib/copyreg.py
copyreg 模块提供了可在封存特定对象时使用的一种定义函数方式。 pickle 和 copy 模块会在封存/拷贝特定对象时使用这些函数。 此模块提供了非类对象构造器的相关配置信息。 这样的构造器可以是工厂函数或类实例。
- copyreg.pickle(type, function, constructor_ob=None)¶
- Declares that 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. - Note that the - dispatch_tableattribute of a pickler object or subclass of- pickle.Picklercan also be used for declaring reduction functions.
示例¶
以下示例将会显示如何注册一个封存函数,以及如何来使用它:
>>> 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...