1. Dump the object to a file
>>> import pickle
>>> class a:
... def __init__(self):
... pass
... def toString(self):
... print('i am a')
...
>>> a1=a()
>>> with open('k','wb') as f:
... pickle.dump(a1,f)
...
2. Dump objects as strings available pickle.dumps
>>> p=pickle.dumps(a1)
3. If you get the object from a file or string, you can use the pickle.load and pickle.loads methods
>>> #从文件中恢复对象
>>> r=open('k','rb')
>>> a2=pickle.load(r)
>>> r.close()
>>> #从字符串中恢复对象
>>> s=pickle.dumps(a1)
>>> s
b'\x80\x03c__main__\na\nq\x00)\x81q\x01.'
>>> a3=pickle.loads(s)
>>> a3
<__main__.a object at 0x7fe23f3c13c8>
For most programs, mastering the load and dump methods can make efficient use of the pickle module. The pickle module is compatible with most Python data types and user-defined class instances.