您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python pickle类库介绍(对象序列化和反序列化)

5b51 2022/1/14 8:18:07 python 字数 6632 阅读 381 来源 www.jb51.cc/python

一、pickle pickle模块用来实现python对象的序列化和反序列化。通常地pickle将python对象序列化为二进制流或文件。

概述

一、pickle

pickle模块用来实现python对象的序列化和反序列化。通常地pickle将python对象序列化为二进制流或文件
 
python对象与文件间的序列化和反序列化:

注意:对于函数或类的序列化是以名字来识别的,所以需要import相应的module。

二、pickle的运行过程

在大部分情况下,要是的对象picklable,我们不需要额外的代码认地pickle将智能地检查类和实例的属性,当一个类实例反序列化的时候,它的__init__()方法通常不被调用。而是首先创建一个未初始化的实例,然后再回复存储的属性
 

但是可以通过实现下列的方法修改认的行为:

有的时候为了效率,或上面的3个函数不能满足需求时,需要实现__reduce__()函数

三、实例

# 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类型的认行为  

    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

总结

以上是编程之家为你收集整理的Python pickle类库介绍(对象序列化和反序列化)全部内容,希望文章能够帮你解决Python pickle类库介绍(对象序列化和反序列化)所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶