Python设计模式 字符串和序列化
字符串序列化是将对象的状态写入字节流的过程。在python中,”pickle “库被用来实现序列化。这个模块包括一个强大的算法,用于序列化和反序列化Python对象结构。”pickling “是将Python对象层次结构转换为字节流的过程,”unpickling “则是相反的过程。
腌制模块的演示如下:
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)
输出
上述程序产生了以下输出 –