I want my class to implement Save and Load functions which simply do a pickle of the class. But apparently you cannot use 'self' in the fashion below. How can you do this?
self = cPickle.load(f)
cPickle.dump(self,f,2)
I want my class to implement Save and Load functions which simply do a pickle of the class. But apparently you cannot use 'self' in the fashion below. How can you do this?
self = cPickle.load(f)
cPickle.dump(self,f,2)
There is an example of how to pickle an instance here, in the docs. (Search down for the "TextReader" example). The idea is to define __getstate__
and __setstate__
methods, which allow you to define what data needs to be pickled, and how to use that data to re-instantiate the object.
The dump part should work as you suggested. for the loading part, you can define a @classmethod that loads an instance from a given file and returns it.
@classmethod
def loader(cls,f):
return cPickle.load(f)
then the caller would do something like:
class_instance = ClassName.loader(f)
How about writing a class called Serializable that would implement dump and load and make your class inherit from it?
This is what I ended up doing. Updating the __dict__
means we keep any new member variables I add to the class and just update the ones that were there when the object was last pickle'd. It seems the simplest while maintaining the saving and loading code inside the class itself so calling code just does an object.Save().
def Load(self):
f = open(self.filename,'rb')
tmp_dict = cPickle.load(f)
f.close()
self.__dict__.update(tmp_dict)
def Save(self):
f = open(self.filename,'wb')
cPickle.dump(self.__dict__,f,2)
f.close()