Python Design Patterns 简明教程

Strings and Serialization

字符串序列化是将对象的状态写入字节流的过程。在 Python 中,“pickle”库用于启用序列化。该模块包括用于序列化和反序列化 Python 对象结构的强大算法。“酸洗”是将 Python 对象层次结构转换为字节流的过程,“去酸洗”是相反的过程。

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)

Output

上述程序生成以下输出 −

serialization