属性取消酸洗时出错:无法获取属性'位置' [英] AttributeError while unpickling: Can't get attribute 'Location'

查看:0
本文介绍了属性取消酸洗时出错:无法获取属性'位置'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为库存系统编写一个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。写入似乎工作正常,但我无法检查。

我如何修复此问题?

推荐答案

读取泡菜代码需要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文件:

>>> 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的类定义,就像我的示例一样。

这篇关于属性取消酸洗时出错:无法获取属性&#39;位置&#39;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆