Roy Tang

Programmer, engineer, scientist, critic, gamer, dreamer, and kid-at-heart.

Blog Notes Photos Links Archives About

In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it?

That is:

obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the func variable?


Use “getattr”:

obj = MyClass()
    func = getattr(obj, "dostuff")
except AttributeError:
    print "dostuff not found"
I’m curious about why you would need to do this. This sounds like you may be doing something the hard way. Could you elaborate on your situation?
I have a cli app where I want to accept commands from the command line, but don’t want to do something like: “if command = ‘doThing’ then obj.doThing() elseif command = ‘someOtherThing’ … and so on. I want to add methods to the handler class and then they’d automatically be available on the cli
is that alright to do that? what situations would this approach not a good idea? i’m in a similar situation too, but i’m not sure if i’ll go this way. somehow, i feel that it would be more clearer if i explicitly use branching instead. what do you think? thanks!