Python pickle类库介绍(对象序列化和反序列化)
作者:junjie 发布时间:2021-12-31 00:28:33
一、pickle
pickle模块用来实现python对象的序列化和反序列化。通常地pickle将python对象序列化为二进制流或文件。
python对象与文件之间的序列化和反序列化:
pickle.dump()
pickle.load()
如果要实现python对象和字符串间的序列化和反序列化,则使用:
pickle.dumps()
pickle.loads()
可以被序列化的类型有:
* None,True 和 False;
* 整数,浮点数,复数;
* 字符串,字节流,字节数组;
* 包含可pickle对象的tuples,lists,sets和dictionaries;
* 定义在module顶层的函数:
* 定义在module顶层的内置函数;
* 定义在module顶层的类;
* 拥有__dict__()或__setstate__()的自定义类型;
注意:对于函数或类的序列化是以名字来识别的,所以需要import相应的module。
二、pickle的运行过程
在大部分情况下,要是的对象picklable,我们不需要额外的代码。默认地pickle将智能地检查类和实例的属性,当一个类实例反序列化的时候,它的__init__()方法通常不被调用。而是首先创建一个未初始化的实例,然后再回复存储的属性。
但是可以通过实现下列的方法来修改默认的行为:
object.__getstate__() :默认地序列化对象的__dict__,但是如果你实现了__getstate__(),则__getstate__()函数返回的值将被序列化。
object.__setstate__(state) :如果类型实现了此方法,则在反序列化的时候,此方法用来恢复对象的属性。
object.__getnewargs__() : 如果实例构造的时候(__new__())需要参数,则需要实现此函数。
注意:如果__getstate__()返回False,则在反序列化的时候__setstate__()则不被调用。
有的时候为了效率,或上面的3个函数不能满足需求时,需要实现__reduce__()函数。
三、实例
import pickle
# An arbitrary collection of objects supported by pickle.
data = {
'a': [1, 2.0, 3, 4+6j],
'b': ("character string", b"byte string"),
'c': set([None, True, False])
}
with open('data.pickle', 'wb') as f:
# Pickle the 'data' dictionary using the highest protocol available.
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
with open('data.pickle', 'rb') as f:
# The protocol version used is detected automatically, so we do not
# have to specify it.
data = pickle.load(f)
print(str(data))
四、修改picklable类型的默认行为
class TextReader:
"""Print and number lines in a text file."""
def __init__(self, filename):
self.filename = filename
self.file = open(filename)
self.lineno = 0
def readline(self):
self.lineno += 1
line = self.file.readline()
if not line:
return None
if line.endswith('\n'):
line = line[:-1]
return "%i: %s" % (self.lineno, line)
def __getstate__(self):
# Copy the object's state from self.__dict__ which contains
# all our instance attributes. Always use the dict.copy()
# method to avoid modifying the original state.
state = self.__dict__.copy()
# Remove the unpicklable entries.
del state['file']
return state
def __setstate__(self, state):
# Restore instance attributes (i.e., filename and lineno).
self.__dict__.update(state)
# Restore the previously opened file's state. To do so, we need to
# reopen it and read from it until the line count is restored.
file = open(self.filename)
for _ in range(self.lineno):
file.readline()
# Finally, save the file.
self.file = file
reader = TextReader("hello.txt")
print(reader.readline())
print(reader.readline())
s = pickle.dumps(reader)
#print(s)
new_reader = pickle.loads(s)
print(new_reader.readline())
# the output is
# 1: hello
# 2: how are you
# 3: goodbye
猜你喜欢
- oracle数据库的快照是一个表,它包含有对一个本地或远程数据库上一个或多个表或视图的查询的结果。正因为快照是一个主表的查询子集,使用快照可
- 打开在节点中加入一句:max_allowed_packet=5M 将MySQL的容量扩大到5M  
- 如何在SQL2000的查询中使用XML-Data?具体程序如下:orders.asp<%@ Language=VBScrip
- 最近在学python的过程中无意间发现一个python库:wxpy,其可以实现让微信自动接收、处理消息并进行回复的一系列功能。感觉挺有意思的
- 思路改进原博主文章(Python GUI–Tkinter简单实现个性签名设计)的代码,原先的代码是基于Python2的,我这份代码基于Pyt
- 原文:http://www.smashingmagazine.com/ ... emarkable-favicons/翻译:Blank(怿飞
- 耦合两个或以上的体系或两种运动形式间相互作用而彼此影响以至于联合起来的现象。在软件工程中,对象之间的耦合度就是对象之间的依赖性,对象之间的耦
- 你知道SQL Server这么庞大的企业级数据库服务器产品是如何build出来的吗?这有些相关的数据:每个build 的大小在300GB左右
- 项目地址:https://github.com/chen0495/pythonCrawlerForJSU环境python 3.5即以上req
- 本程序有两文件test.asp 和tree.asp 还有一些图标文件 1。test.asp 调用类生成树 代码如下<%@
- 如何清除Vbscript惹出来的中文乱码? <script language=vbscript runat=s
- 微软昨天在其2009年专业开发者大会上展示了下一个版本的Internet Explorer浏览器IE9。尽管只是一个早期版本,IE开发团队还
- 问题一个已经有内容的 textarea 元素,在执行该元素的 .focus() 方法后,不同的浏览器有不同表现。我们的预期是能够出现在内容后
- 如果备份的数据库有2个文件,分别是.LDF 和 .MDF,打开企业管理器,在实例上右击---所有任务--附加数据库,然后选择那个.MDF文件
- 使用MySQL的命令终端时,如果输入SQL有误,将有beep声。若要关闭该功能,根据mysql --help,使用mysql --no-be
- 如果你的PHP网站换了空间,必定要对Mysql数据库进行转移,一般的转移的方法,是备份再还原,有点繁琐,而且由于数据库版本的不一样会导致数据
- URL完全匹配(具体的url)/indexURL模糊匹配(你根本就不知道index后面是什么,它根本不会返回参数)/index/\dURL带
- <%dim total(7,1) total(1,0)="中国经营报"
- 一、简介主流被使用的地理坐标系并不统一,常用的有WGS84、GCJ02(火星坐标系)、BD09(百度坐标系)以及百度地图中保存矢量信息的we
- 一.GUI(Graphical User Interface(图形用户接口))1.导入需要用到的包import tkinter as tki