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'x80x03c__main__
Foo
qx00)x81qx01}qx02Xx03x00x00x00valqx03Kx04sb.'
I'm being unpickled with these values: {'val': 4}
<__main__.Foo object at 0x0000028927245B70>