2010-01-02 94 views
1
# Example: provide pickling support for complex numbers. 

try: 
    complex 
except NameError: 
    pass 
else: 

    def pickle_complex(c): 
     return complex, (c.real, c.imag) # why return complex here? 

    pickle(complex, pickle_complex, complex) 

为什么?
以下代码是被调用的函数泡菜:为什么此代码返回'复杂'?

dispatch_table = {} 

def pickle(ob_type, pickle_function, constructor_ob=None): 
    if type(ob_type) is _ClassType: 
     raise TypeError("copy_reg is not intended for use with classes") 

    if not callable(pickle_function): 
     raise TypeError("reduction functions must be callable") 
    dispatch_table[ob_type] = pickle_function 

    # The constructor_ob function is a vestige of safe for unpickling. 
    # There is no reason for the caller to pass it anymore. 
    if constructor_ob is not None: 
     constructor(constructor_ob) 

def constructor(object): 
    if not callable(object): 
     raise TypeError("constructors must be callable") 
+0

你能提供你所看到的到底是什么行为,你正期待一些更详细? –

+0

此代码从哪里来? – 2010-01-02 06:24:32

+1

@Roger,代码从标准Python发行的copy_reg.py模块。 copy_reg.py中的 – Theran

回答

3

complex是类使用以重构腌对象。它被返回,以便它可以与真实和图像值一起腌制。然后,当Unpickler会出现时,它看到的类和一些值作为参数传递给它的构造函数中使用。该Unpickler会使用给定的类和参数来创建一个新的complex对象,它是相当于在酸洗原来的一个。

这在更详细的copy_regpickle documentation说明。