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 "", line 1, in
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!!
解决方案
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.