Search code examples
pythonobjectwxpythongetattr

Getattr on self not working, is it supposed to work?


I have this very simple function inside an object:

def ctrl_btn_press(self, event):
    print event.GetEventObject().GetName()
    getattr(self, event.GetEventObject().GetName())

Event is a wxpython Event. The names are in a list in a config file and buttons in my gui are set to the names of functions in this event handler object that will handle that button press.

The print works, it prints, for example, "alm_switch_away". The function call getattr doesn't work, however. This is the function it is supposed to call (with print functions to test if the code "got there") but nothing gets printed:

def alm_switch_away(self):
    print "HERE!"

Can you see what I'm doing incorrectly?


Solution

  • If by does't work you mean I get an AttributeError instead, then you need to look at the string representation output instead to spot any non-printable characters in the event name:

    print repr(event.GetEventObject().GetName())
    

    If you mean nothing actually happens then that's because you never do anything with the method you looked up. You are not calling the method. Add () after the getattr() call:

    event_method = getattr(self, event.GetEventObject().GetName())
    event_method()
    

    or combined into one line:

    getattr(self, event.GetEventObject().GetName())()