gpt4 book ai didi

python - 可以对顶级类(class)进行 pickle 和 unpickled(文档有误吗?)

转载 作者:太空宇宙 更新时间:2023-11-04 08:51:56 24 4
gpt4 key购买 nike

下面链接的文档似乎说可以 pickle 顶级类及其实例。但基于我之前的回答 question这似乎不正确。在我发布的脚本中,pickle 接受类对象并写入一个文件,但这没有用。

这是我的问题:这个文档是错误的,还是有一些我不明白的更微妙的地方?此外,在这种情况下,pickle 是否应该生成某种错误消息?

https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled ,

The following types can be pickled:

  • None, True, and False
  • integers, long integers, floating point numbers, complex numbers
  • normal and Unicode strings
  • tuples, lists, sets, and dictionaries containing only picklable objects
  • functions defined at the top level of a module
  • built-in functions defined at the top level of a module
  • classes that are defined at the top level of a module ( my bold )
  • instances of such classes whose dict or the result of calling getstate() > is picklable (see section The pickle protocol for details).

最佳答案

创建一个定义在模块顶层的类:

foo.py:

class Foo(object): pass

然后运行一个单独的脚本,

脚本.py:

import pickle
import foo


with open('/tmp/out.pkl', 'w') as f:
pickle.dump(foo.Foo, f)

del foo

with open('/tmp/out.pkl', 'r') as f:
cls = pickle.load(f)

print(cls)

打印

<class 'foo.Foo'>

请注意,pickle 文件 out.pkl 仅包含 strings,它们命名定义模块和类的名称。它不存储类的定义:

cfoo
Foo
p0
.

因此,在 unpickling 时定义模块 foo 必须包含类的定义。如果从定义模块中删除该类

del foo.Foo

然后你会得到错误

AttributeError: 'module' object has no attribute 'Foo'

关于python - 可以对顶级类(class)进行 pickle 和 unpickled(文档有误吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34314022/

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