为什么这段代码会返回'复杂'?

时间:2010-01-02 06:12:37

标签: python pickle complex-numbers

# 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)

为什么?
以下代码是被调用的pickle函数:

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")

1 个答案:

答案 0 :(得分:3)

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

copy_regpickle documentation中详细说明了这一点。