Python:使用pickle模块保存和加载对象时出错 [英] Python: Errors saving and loading objects with pickle module
问题描述
我正在尝试用这段代码加载和保存对象,这是我从一个星期前问的一个问题得到的:
I am trying to load and save objects with this piece of code I get it from a question I asked a week ago: Python: saving and loading objects and using pickle.
这段代码是这样的:
class Fruits: pass
banana = Fruits()
banana.color = 'yellow'
banana.value = 30
import pickle
filehandler = open("Fruits.obj","wb")
pickle.dump(banana,filehandler)
filehandler.close()
file = open("Fruits.obj",'rb')
object_file = pickle.load(file)
file.close()
print(object_file.color, object_file.value, sep=', ')
乍一看,这段代码可以很好地工作,可以加载并查看已保存对象的颜色"和值".
但是,我追求的是关闭一个会话,打开一个新会话,然后加载我在上一个会话中保存的内容.在行filehandler.close()
之后关闭会话,然后打开一个新的行,然后放置其余的代码,然后在object_file = pickle.load(file)
之后输入以下错误:
At a first glance the piece of code works well, getting load and see the 'color' and 'value' of the saved object.
But, what I pursuit is to close a session, open a new one and load what I save in a past session. I close the session after putting the line filehandler.close()
and I open a new one and I put the rest of your code, then after putting object_file = pickle.load(file)
I get this error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
object_file = pickle.load(file)
File "C:\Python31\lib\pickle.py", line 1365, in load
encoding=encoding, errors=errors).load()
AttributeError: 'module' object has no attribute 'Fruits'
任何人都可以向我解释此错误消息的含义,并告诉我如何解决此问题吗?
Can anyone explain me what this error message means and telling me how to solve this problem?
非常感谢,新年快乐!
推荐答案
Python不会腌制整个类.只有名字.因此,您必须将包含它们的模块保存到文件中,并且在取消它们腌制时可以导入.然后,Python将重新导入它们.
Python does not pickle whole classes. Only the names. Therefore you must have the module that contains them saved to a file and importable at the time they are unpickled. Python will then re-import them.
如果遇到问题,则可能需要定义用于腌制的特殊辅助方法__getstate__
和__setstate__
.
If you run into problems, you may need to define special helper methods, __getstate__
and __setstate__
that are used for pickling.
这篇关于Python:使用pickle模块保存和加载对象时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!