pickle 读取代码需要定义Location
班级。如果不是,它将无法重建该类的自定义对象。
# config_writer.py
import pickle
class Location:
def __init__(self, store, aisle):
self.store = store
self.aisle = aisle
locations = [Location(i, i) for i in range(10)]
with open('.config/autosave.bin', 'wb') as f:
pickle.dump(locations, f)
这是一个尝试在没有类定义的情况下读取 pickle 文件的示例Location
(在另一个终端/会话中运行此代码):
>>> import pickle
>>> with open('.config/autosave.bin','rb') as f:
... data = pickle.load(f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
AttributeError: Can't get attribute 'Location' on <module '__main__' (built-in)>
但是,通过访问类定义:
>>> from config_writer import Location
>>> with open('.config/autosave.bin','rb') as f:
... data = pickle.load(f)
>>> data
[<config_writer.Location object at 0x7f8b472111d0>, <config_writer.Location object at 0x7f8b41ad6e48>, <config_writer.Location object at 0x7f8b41adb0f0>, <config_writer.Location object at 0x7f8b41adb128>, <config_writer.Location object at 0x7f8b41adb160>, <config_writer.Location object at 0x7f8b41adb198>, <config_writer.Location object at 0x7f8b41adb1d0>, <config_writer.Location object at 0x7f8b41adb208>, <config_writer.Location object at 0x7f8b41adb240>, <config_writer.Location object at 0x7f8b41adb278>]
希望读取 pickle 文件的代码能够导入类定义Location
来自其他一些模块,就像我的示例一样。