歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python pickle模塊的簡單使用筆記

Python pickle模塊的簡單使用筆記

日期:2017/3/1 9:32:09   编辑:Linux編程

Python pickle 模塊提供了把對象序列化的方法,對象會被序列化成ASCII的字符串,可以保存到文件。unpickle則可以從文件或字符中反序列化成對象。如下的兩個方法非常有用。

pickle.dumps(obj[, protocol])

Return the pickled representation of the object as a string, instead of writing it to a file.

If the protocol parameter is omitted, protocol 0 is used. If protocol is specified as a negative value or HIGHEST_PROTOCOL, the highest protocol version will be used.

Changed in version 2.3: The protocol parameter was added.

pickle.loads(string)
Read a pickled object hierarchy from a string. Characters in the string past the pickled object’s representation are ignored.

我在使用wx時,wxGrid的GetCellValue方法只能返回字符串。但我希望它可以返回我定義的對象,於是我找到了pickle。我在類中重寫__str__()方法,使用pickle來序列化這個對象。

例子:

import pickle
class LineProperty:
    def __init__(self, width=0, shape=0xFFFF, r=0, g=0, b=0, color=0):
        self.width = width
        self.shape = shape
        self.r = r
        self.g = g
        self.b = b
        self.color = color
    #使用pickle 序列化    
    def __str__(self):
        return pickle.dumps(self)

然後我在自己定義的wxGridTable中設置了這個數據,GridCellEditor中的重寫的

BeginEditor方法

class LineGridCellEditor(grd.PyGridCellEditor):
    def Create(self, parent, id, evtHandler):
        self._control = wx.Control(parent, id, wx.DefaultPosition, (100, 100))
        self._parent = parent
        self.SetControl(self._control)
 
        newEvt = wx._core.EvtHandler()
        if newEvt:
            self._control.PushEventHandler(newEvt)
        self.startValue = self.endValue = None
        self.m_canvas = linecanvas.MyLineCanvas(self._control)
 
    def OnClick(self, evt):
        pass
 
    def Clone(self):
        return LineGridCellEditor()
 
    def BeginEdit(self, row, col, grid):
        self.startValue = grid.GetCellValue(row, col)

#在這裡反序列化,傳遞給canvas

        self.m_canvas.SetScales(pickle.loads(str(self.startValue)))

這樣就可以擺脫GetCellValue只能返回wxString的限制了。把對象傳輸過來,用glCanvas來繪制。

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved