tags:

views:

87

answers:

2

i don't know what__setstate__ __getstate__ does ,so help me use a simple example,thanks

__setstate__ __getstate__

A: 

These methods are used for controlling how objects are pickled and unpickled by the pickle module. This is usually handled automatically, so unless you need to override how a class is pickled or unpickled you shouldn't need to worry about it.

Pär Wieslander
+1  A: 

Here's a very simple example that should supplement the pickle docs.

class Foo(object):
def __init__(self, val=2):
        self.val = val
def __getstate__(self):
    print 'im being pickled'
    self.val *= 2
    return self.__dict__
def __setstate__(self, d):
    print 'im being unpickled with these values', d
    self.__dict__ = d
    self.val *= 3

import pickle
f = Foo()
f_string = pickle.dumps(f)
f_new = pickle.loads(s)
BrainCore