我正在使用字典来存储对象。然后将词典存储在一个工具架文件中。当从用于打印内容的工具架文件中检索字典时,它会出错。
以下脚本用于创建一个用于测试的工具架文件:
# creating shelf file for testing
import shelve
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 9)
miles = Dog("Miles", 4)
d = {}
d['buddy'] = buddy
d['miles'] = miles
with shelve.open('dogs') as sf:
sf['d'] = d
然后,以下脚本读取上面创建的机框文件:
# reading shelf file and printing stuff
import shelve
with shelve.open('dogs') as sf:
d = sf['d']
for k in d.keys():
print(d[k].name, d[k].age)
运行上述脚本后,它会收到以下错误消息:
Traceback (most recent call last):
File "C:UsersjcAppDataLocalProgramsPythonPython39libshelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'd'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:UsersjcOneDriveDocumentsPythonScriptstest2.py", line 23, in <module>
d = sf['d']
File "C:UsersjcAppDataLocalProgramsPythonPython39libshelve.py", line 114, in __getitem__
value = Unpickler(f).load()
AttributeError: Can't get attribute 'Dog' on <module '__main__' from 'c:\Users\jc\OneDrive\Documents\PythonScripts\test2.py'>
问题是读取保存的机框的脚本不知道Dog
类的定义。
CCD_ 2基于CCD_ 3模块。pickle
可以序列化类的实例,但它不序列化类本身。类定义必须存在于读取搁置数据的模块中。
引用文件:
pickle可以透明地保存和恢复类实例,但是类定义必须是可导入的,并且与存储对象时位于同一模块中。
如果在读取机框之前确保脚本中有Dog
的定义,则保存的数据将正确加载。