Simple example of use of __setstate__ and __getstate__

前端 未结 3 1606
夕颜
夕颜 2020-12-02 10:27

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

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 10:58

    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)
    

提交回复
热议问题