Python pickle instance variables -


i doing calculations on instance variable, , after done want pickle class instance, such don't have calculations again. here example:

import cpickle pickle  class test(object):     def __init__(self, a, b):         self.a =         self.b = b         self.c = none     def compute(self, x):         print 'calculating c...'         self.c = x * 2  test = test(10, 'hello') test.compute(6)  # have computed c , want store it, don't have recompute again:  pickle.dump(test, open('test_file.pkl', 'wb')) 

after test.compute(6) can check see test.__dict__ is:

>>> test.__dict__ {'a': 10, 'c': 12, 'b': 'hello'} 

i thought going pickled; however,

when go load class instance:

import cpickle pickle  pickle_class_object import test  t2 = pickle.load(open('test_file.pkl', 'rb')) 

i see in shell:

calculating c... 

which means did not pickle c , computing on again.

is there way pickle test how want to? don't have compute c on again. see pickle test.__dict__, wondering if there better solutions. also, understanding going on here weak, comment going great. i've read __getstate__ , __setstate__, don't see how apply them here.

pickling works expect work. problem here when run new script, import module contains class test. entire module run including bit create test.

the typical way handle sort of thing protect stuff in if __name__ == "__main__: block.

class test(object):     def __init__(self, a, b):         self.a =         self.b = b         self.c = none     def compute(self, x):         print 'calculating c...'         self.c = x * 2  if __name__ == "__main__":     import cpickle pickle      test = test(10, 'hello')     test.compute(6)      # have computed c , want store it, don't have recompute again:      pickle.dump(test, open('test_file.pkl', 'wb')) 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -