Python内置的pickle模块能够将Python对象序列成字节流,也可以把字节流反序列成对象。
import pickle
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def say(self):
print("I am", self.name)
>>> t = Student('Tom', 23)
>>> t.say()
I am Tom
>>>
>>> save_path = './tom_msg'
>>> with open(save_path, 'wb') as f: # 字节流写入
... pickle.dump(t, f) # 序列化数据保存在文件中
>>>
>>> with open(save_path, 'rb') as f: # 字节流读出
... after_t = pickle.load(f) # 读取文件信息反序列化成对象
...
>>> after_t.__dict__
{'name': 'Tom', 'age': 23}
>>> after_t.say()
I am Tom
>>>
>>>
>>> l = Student('Lisa', 23)
>>> serialized = pickle.dumps(l)
>>> serialized
b'\x80\x03c__main__\nStudent\nq\x00)\x81q\x01}q\x02(X\x04\x00\x00\x00nameq\x03X\x04\x00\x00\x00Lisaq\x04X\x03\x00\x00\x00ageq\x05K\x17ub.'
>>> after_l = pickle.loads(serialized)
>>> after_l.say()
I am Lisa
>>> after_l.__dict__
{'name': 'Lisa', 'age': 23
如果比较复杂的操作(对象属性更变,添加删除),pickle模块可能会出问题,那时候应该结合copyreg来使用