gpt4 book ai didi

python - 解封 : Can't get attribute 'Location' 时出现 AttributeError

转载 作者:行者123 更新时间:2023-11-28 22:22:24 24 4
gpt4 key购买 nike

我正在为库存系统编写 Python CGI 脚本。它需要通过 pickle 存储一个对象列表(称为 locations)。这是我正在使用的代码:

try:
with open(".config/autosave.bin", "rb") as dataFile:
locations = pickle.load(dataFile)
except (FileNotFoundError, PermissionError):
dispHTML("p", contents="Error in load: Save file incorrectly configured!")
locations = []

但是,这会导致:

 /Applications/MAMP/cgi-bin/ic/main.py in ()
16 try:
17 with open(".config/autosave.bin", "rb") as dataFile:
=> 18 locations = pickle.load(dataFile)
19 except (FileNotFoundError, PermissionError):
20 dispHTML("p", contents="Error in load: Save file incorrectly configured!")
AttributeError: Can't get attribute 'Location' on <module '__main__' from '/Applications/MAMP/cgi-bin/ic/main.py'>
args = ("Can't get attribute 'Location' on <module '__main__' from '/Applications/MAMP/cgi-bin/ic/main.py'>",)
with_traceback = <built-in method with_traceback of AttributeError object>

如您所见,保存文件存储在 .config/autosave.bin 中。写入它似乎工作正常,但我无法检查。

我该如何解决这个问题?

最佳答案

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)

这是一个尝试在没有 Location 类定义的情况下读取 pickle 文件的示例(在另一个终端/ session 中运行此代码):

>>> 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 的类定义。

关于python - 解封 : Can't get attribute 'Location' 时出现 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47713175/

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