Simple example of use of __setstate__ and __getstate__
class Foo(object): def __init__(self, val=2): self.val = val def __getstate__(self): print ("I'm being picked") self.val *= 2 return self.__dict__ def __setstate__(self, d): print("I'm being unpickled with these values:", d) self.__dict__ = d self.val *= 3 import pickle f = Foo() f_string = pickle.dumps(f) # 带s的,可以理解为string print(f_string) f_new = pickle.loads(f_string) print(f_new)
I'm being picked
b'\x80\x03c__main__\nFoo\nq\x00)\x81q\x01}q\x02X\x03\x00\x00\x00valq\x03K\x04sb.'
I'm being unpickled with these values: {'val': 4}
<__main__.Foo object at 0x0000028927245B70>
新战场:https://blog.csdn.net/Stephen___Qin