前言
Python3的序列化和反序列化学习笔记
引入依赖
直接输出
序列化
1
| bytes = pickle.dumps(<obj>)
|
反序列化
1
| obj = pickle.loads(<bytes>)
|
输出到文件
<str>:JSON格式字符串
序列化
1 2
| with open("<file>", "w") as f: bytes = pickle.dump(<obj>, f)
|
反序列化
1 2
| with open("<file>", "r") as f: obj = pickle.load(f)
|
魔法方法
reduce()
- 序列化时会自动执行
__reduce__()方法,但不得到返回值
- 反序列化时会得到
__reduce__()方法的返回值
1 2 3 4
| class 类名: def __reduce__(self): ... return (self.__class__, ())
|
setstate()
- 序列化时会自动执行
__getstate__()方法
- 反序列化时会自动执行
__setstate__()方法
1 2 3 4 5
| class 类名: def __getstate__(self): ... def __setstate__(self): ...
|
完成
参考文献
哔哩哔哩——xiaodisec
哔哩哔哩——骆昊jackfrued