Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python pickle模块的简单使用笔记

Python pickle 模块提供了把对象序列化的方法,对象会被序列化成ASCII的字符串,可以保存到文件。unpickle则可以从文件或字符中反序列化成对象。如下的两个方法非常有用。
pickle.dumpsobj[, 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.loadsstring
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 pickleclass LineProperty:def __init__(self, width=0, shape=0xFFFF, r=0, g=0, b=0, color=0):self.width = widthself.shape = shapeself.r = rself.g = gself.b = bself.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 = parentself.SetControl(self._control) newEvt = wx._core.EvtHandler()if newEvt:self._control.PushEventHandler(newEvt)self.startValue = self.endValue = Noneself.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.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里
Python 的下载地址:请点这里 本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-02/114042.htm