Class Persistence using __dict__

Gene C gchiaramonte at yahoo.com
Mon Sep 4 15:55:27 CEST 2000


I want to add simple persistence to some of my python classes using cPickle.
I have seen where others have stored all the class data in a dictionary
(self.data = {}) then dump and load the dictionary from within the class. I
want something more robust that will also save and load any new class data I
might add to the class on the fly. The following seems to work fine. I was
wondering if some python experts might have any comments/suggestions.
Thanks. Gene

class Test:
    def __init__(self):
        self.id = 1
        self.name = "Test Class"
        self.my_list = [1,2,3]

    def Save(self, fn):
        f = open(fn, "w")
        cPickle.dump(self.__dict__, f)

    def Load(self, fn):
        f = open(fn, "r")
        self.__dict__ = cPickle.load(f)

# now I can do this...
t = Test()
t.new_data = 'hi there'
t.Save('c:\\test.pkl')

t1 = Test()
t1.Load('c:\\test.pkl')
t1.new_data    # prints 'hi there'






More information about the Python-list mailing list