Skip to main content
 首页 » 编程设计

python之尝试检索搁置类时的 KeyError 和 AtributeError之Python 3.6

2024年12月31日9sxdcgaq8080

在一个程序中序列化一个类时(搁置),我无法在不收到以下错误的情况下检索它:

 File "\Python36_64\lib\shelve.py", line 111, in __getitem__ 
    value = self.cache[key] 
KeyError: 'foo' 
 
During handling of the above exception, another exception occurred: 
 
Traceback (most recent call last): 
  File "program.py", line 12, in <module> 
    bar = db['foo'] 
  File "\Python36_64\lib\shelve.py", line 114, in __getitem__ 
    value = Unpickler(f).load() 
AttributeError: Can't get attribute 'bar' on <module '__main__' (built-in)> 

这是我初始化货架的代码。它编译:

import shelve  
class bar: 
   x = {} 
db = shelve.open('file.dat') 
db['foo'] = bar 

我一直在尝试使用以下代码在另一个程序中检索类 bar。这没有正确编译。:

import shelve 
db = shelve.open('file.dat') 
bar = db['foo'] 

请您参考如下方法:

您不能像那样通过 pickling 和 unpickling 来存储类。当pickle 需要pickle 一个类时,它只是记录类的模块和名称,而不是内容。 pickle 只能在同一个模块定义了同一个类的环境中被 unpickled。