一、pickle
pickle模塊用來實(shí)現(xiàn)python對(duì)象的序列化和反序列化。通常地pickle將python對(duì)象序列化為二進(jìn)制流或文件。
?
python對(duì)象與文件之間的序列化和反序列化:
pickle.dump()
pickle.load()
如果要實(shí)現(xiàn)python對(duì)象和字符串間的序列化和反序列化,則使用:
pickle.dumps()
pickle.loads()
?
可以被序列化的類型有:
* None,True 和 False;
* 整數(shù),浮點(diǎn)數(shù),復(fù)數(shù);
* 字符串,字節(jié)流,字節(jié)數(shù)組;
* 包含可pickle對(duì)象的tuples,lists,sets和dictionaries;
* 定義在module頂層的函數(shù):
* 定義在module頂層的內(nèi)置函數(shù);
* 定義在module頂層的類;
* 擁有__dict__()或__setstate__()的自定義類型;
?
注意:對(duì)于函數(shù)或類的序列化是以名字來識(shí)別的,所以需要import相應(yīng)的module。
二、pickle的運(yùn)行過程
在大部分情況下,要是的對(duì)象picklable,我們不需要額外的代碼。默認(rèn)地pickle將智能地檢查類和實(shí)例的屬性,當(dāng)一個(gè)類實(shí)例反序列化的時(shí)候,它的__init__()方法通常不被調(diào)用。而是首先創(chuàng)建一個(gè)未初始化的實(shí)例,然后再回復(fù)存儲(chǔ)的屬性。
?
但是可以通過實(shí)現(xiàn)下列的方法來修改默認(rèn)的行為:
object.__getstate__() :默認(rèn)地序列化對(duì)象的__dict__,但是如果你實(shí)現(xiàn)了__getstate__(),則__getstate__()函數(shù)返回的值將被序列化。
object.__setstate__(state) :如果類型實(shí)現(xiàn)了此方法,則在反序列化的時(shí)候,此方法用來恢復(fù)對(duì)象的屬性。
object.__getnewargs__() : 如果實(shí)例構(gòu)造的時(shí)候(__new__())需要參數(shù),則需要實(shí)現(xiàn)此函數(shù)。
注意:如果__getstate__()返回False,則在反序列化的時(shí)候__setstate__()則不被調(diào)用。
有的時(shí)候?yàn)榱诵?,或上面?個(gè)函數(shù)不能滿足需求時(shí),需要實(shí)現(xiàn)__reduce__()函數(shù)。
三、實(shí)例
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類型的默認(rèn)行為??
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
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
