Python设计模式 - 字符串和序列化

字符串序列化是将对象状态写入字节流的过程.在python中,"pickle"库用于启用序列化.该模块包含一个强大的算法,用于序列化和反序列化Python对象结构. "Pickling"是将Python对象层次结构转换为字节流的过程,"unpickling"是相反的过程.

pickle模块的演示如下 :

import pickle

#Here's an example dict
grades = { 'Alice': 89, 'Bob': 72, 'Charles': 87 }

#Use dumps to convert the object to a serialized string
serial_grades = pickle.dumps( grades )
print(serial_grades)

#Use loads to de-serialize an object
received_grades = pickle.loads( serial_grades )
print(received_grades)

输出

上述程序生成以下输出 :

序列化