尝试检索搁置的 class - Python 时的 KeyError 和 AtributeError 3.6

KeyError and AtrributeError when trying to retrieve a shelved class - Python 3.6

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

 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

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

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

您不能像那样通过酸洗和解酸洗来存储 classes。当pickle 需要pickle 一个class 时,它只记录class 的模块和名称,而不是内容。 pickle 只能在相同模块具有相同 class 定义的环境中被取消。