Python: Errors saving and loading objects with pickle module

纵然是瞬间 提交于 2019-12-23 05:32:08

问题


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.

The piece of code is this:

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=', ')

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?

Thank so much and happy new year!!


回答1:


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.

If you run into problems, you may need to define special helper methods, __getstate__ and __setstate__ that are used for pickling.



来源:https://stackoverflow.com/questions/4573976/python-errors-saving-and-loading-objects-with-pickle-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!