Python pickle 模块提供了把对象序列化的方法,对象会被序列化成ASCII的字符串,能够保存到文件。unpickle则能够从文件或字符中反序列化成对象。以下的两个方法很是有用。python
Return the pickled representation of the object as a string, instead of writing it to a file. canvas
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. spa
Changed in version 2.3: The protocol parameter was added..net
我在使用wx时,wxGrid的GetCellValue方法只能返回字符串。但我但愿它能够返回我定义的对象,因而我找到了pickle。我在类中重写__str__()方法,使用pickle来序列化这个对象。code
例子:对象
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中的重写的ci
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):
passdef Clone(self):
return LineGridCellEditor()
def BeginEdit(self, row, col, grid):
self.startValue = grid.GetCellValue(row, col)#在这里反序列化,传递给canvasget
self.m_canvas.SetScales(pickle.loads(str(self.startValue)))
这样就能够摆脱GetCellValue只能返回wxString的限制了。把对象传输过来,用glCanvas来绘制。string