下面链接的文档似乎说可以 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'
