一、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
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新日志
- 《原神》「星路拾忆」网页活动壁纸展示
- 群星.2024-祝你幸福!电影原声带【阿里巴巴】【FLAC分轨】
- 于台烟.2004-执着【乾坤唱片】【WAV+CUE】
- 黄品源.2004-感谢·情人(引进版)【滚石】【WAV+CUE】
- 《最终幻想16》评测:游、戏两难全的系列转折
- 《纸嫁衣》五部打包¥104,《鬼泣5》仅需¥44
- 《崩坏:星穹铁道》造物大赛卷出新高度
- 《王菲 菲常传奇 2CD》[WAV+CUE][950MB]
- 《王菲 空灵独味唱腔 非常传奇 紫水晶2CD》[WAV+CUE][860MB]
- 《车载专业测试王1号 极品音质》[WAV/分轨][980MB]
- 炉石传说的国服回归送什么奖励 炉石传说9.25回归最新消息介绍
- 云顶之弈最强阵容汇总2024 云顶之弈最强阵容搭配最新版本
- S14lol全球总决赛在哪观看 lol全球总决赛观赛直播地址汇总
- 黄思婷2011-感谢天[豪记唱片][WAV+CUE]
- 孙淑媚2013-太阳[台湾首版][WAV+CUE]