gpt4 book ai didi

python - 为什么此代码返回 'complex' ?

转载 作者:行者123 更新时间:2023-12-01 00:00:02 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于python - 为什么此代码返回 'complex' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1990759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com