python pickle模块的简单使用笔记
2014-06-18 07:12
1376 查看
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来序列化这个对象。例子:
然后我在自己定义的wxGridTable中设置了这个数据,GridCellEditor中的重写的BeginEditor方法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)
这样就可以摆脱GetCellValue只能返回wxString的限制了。把对象传输过来,用glCanvas来绘制。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):passdef Clone(self):return LineGridCellEditor()def BeginEdit(self, row, col, grid):self.startValue = grid.GetCellValue(row, col)#在这里反序列化,传递给canvasself.m_canvas.SetScales(pickle.loads(str(self.startValue)))
相关文章推荐
- logging in python: logging模块的简单使用
- python笔记03 python的简单使用(未完)
- python数据持久存储:pickle模块的基本使用
- Python学习笔记之os模块使用总结
- Python的Socket模块TCP UDP简单使用
- 【转】使用Python中HTTPParser模块进行简单的html解析
- 使用Python中HTTPParser模块进行简单的html解析
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python的md5模块使用非常简单
- [Python学习]Logging模块的简单使用
- python数据持久存储:pickle模块的基本使用 分类: python python基础学习 python 小练习 2013-06-17 14:41 209人阅读 评论(0) 收藏
- python —— 使用logging模块简单实现日志系统
- Logging模块的简单使用 Python
- python处理图片之PIL模块简单使用
- Python 模块paramiko简单使用方法
- Python 模块paramiko简单使用方法
- Python的Socket模块简单使用医
- python中机器学习包scikit-learn使用笔记与sign prediction简单小结
- python数据持久存储:pickle模块的基本使用