【问题标题】:Why does this code return 'complex'?为什么此代码返回“复杂”?
【发布时间】:2010-01-02 06:12:36
【问题描述】:
# 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")

【问题讨论】:

  • 您能否提供更多关于您所看到的行为和预期行为的详细信息?
  • 这段代码来自哪里?
  • @Roger,代码来自标准 Python 发行版中的 copy_reg.py 模块。

标签: python pickle complex-numbers


【解决方案1】:

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

这在copy_reg 和pickle documentation 中有更详细的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2022-06-16
    • 2020-10-04
    相关资源
    最近更新 更多