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