Fix Python – Simple example of use of __setstate__ and __getstate__

Question

Asked By – zjm1126

I don’t know what the __setstate__ and __getstate__ methods do, so help me with a simple example.

Now we will see solution for issue: Simple example of use of __setstate__ and __getstate__


Answer

Here’s a very simple example for Python that should supplement the pickle docs.

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

import pickle
f = Foo()
f_data = pickle.dumps(f)
f_new = pickle.loads(f_data)

Output:

I'm being pickled
I'm being unpickled with these values: {'val': 4}

This question is answered By – BrainCore

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0