Python pickle模块的简单使用笔记


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来绘制。

image

--------------------------------------分割线 --------------------------------------

CentOS上源码安装Python3.4 

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版]

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]

Python脚本获取Linux系统信息

在Ubuntu下用Python搭建桌面算法交易研究环境

Python 语言的发展简史

Python 的详细介绍:请点这里
Python 的下载地址:请点这里 

本文永久更新链接地址:

相关内容