dynamic method question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jesse Aldridge

    dynamic method question

    So in the code below, I'm binding some events to a text control in
    wxPython. The way I've been doing it is demonstrated with the
    Lame_Event_Widg et class. I want to factor out the repeating
    patterns. Cool_Event_Widg et is my attempt at this. It pretty much
    works, but I have a feeling there's a better way of doing this. Also,
    I couldn't get the Cool_Text_Contr ol to override the on_text method.
    How would I do that?

    -------------

    import textwrap, new

    import wx


    class Lame_Event_Widg et:
    def bind_events(sel f):
    self.Bind(wx.EV T_LEFT_DOWN, self.on_left_do wn)
    self.Bind(wx.EV T_RIGHT_DOWN, self.on_right_d own)
    self.Bind(wx.EV T_MIDDLE_DOWN, self.on_middle_ down)
    self.Bind(wx.EV T_LEFT_UP, self.on_left_up )
    self.Bind(wx.EV T_RIGHT_UP, self.on_right_u p)
    self.Bind(wx.EV T_TEXT, self.on_text)

    def on_left_down(se lf, e):
    print "lame normal method: on_left_down"
    e.Skip()

    def on_right_down(s elf, e):
    print "lame normal method: on_right_down"
    e.Skip()

    def on_middle_down( self, e):
    print "lame normal method: on_middle_down"
    e.Skip()

    def on_left_up(self , e):
    print "lame normal method: on_left_up"
    e.Skip()

    def on_right_up(sel f, e):
    print "lame normal method: on_right_up"
    e.Skip()

    def on_text(self, e):
    print "lame normal method: on_text"
    e.Skip()


    class Cool_Event_Widg et:
    def bind_events(sel f):
    method_names = textwrap.dedent (
    """
    on_left_down, on_right_down, on_middle_down,
    on_left_up, on_right_up, on_middle_up,
    on_text"""
    ).replace("\n", "").split(" , ")

    for name in method_names:
    event_name = name.partition( "_")[2]
    event_name = "wx.EVT_" + event_name.uppe r()

    exec("def " + name + "(self, e):\n" +
    " print 'cool dynamic method: " + name + "'\n" +
    " e.Skip()\n"
    "self." + name + " = new.instancemet hod(" + name + ",
    self, self.__class__) \n"
    "self.Bind( " + event_name + ", self." + name + ")")


    if __name__ == "__main__":
    app = wx.App()
    frame = wx.Frame(None)
    panel = wx.Panel(frame)
    sizer = wx.BoxSizer(wx. VERTICAL)
    panel.SetSizer( sizer)

    class Cool_Text_Contr ol(wx.TextCtrl, Cool_Event_Widg et):
    def __init__(self, parent):
    wx.TextCtrl.__i nit__(self, parent)
    self.bind_event s()

    def on_text(self, e):
    print "modified text in Cool_Text_Contr ol"

    class Lame_Text_Contr ol(wx.TextCtrl, Lame_Event_Widg et):
    def __init__(self, parent):
    wx.TextCtrl.__i nit__(self, parent)
    self.bind_event s()

    def on_text(self, e):
    print "modified text in Lame_Text_Contr ol"

    sizer.Add(Cool_ Text_Control(pa nel))
    sizer.Add(Lame_ Text_Control(pa nel))

    frame.Show()
    app.MainLoop()
Working...