86

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?
Georgy
  • 12,464
  • 7
  • 65
  • 73
Roy Tang
  • 5,643
  • 9
  • 44
  • 74
  • 1
    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? – JoshD Oct 17 '10 at 03:06
  • 1
    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 – Roy Tang Oct 17 '10 at 05:07
  • 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! – ultrajohn Sep 03 '12 at 11:59

1 Answers1

105

Use the getattr built-in function. See the documentation

obj = MyClass()
try:
    func = getattr(obj, "dostuff")
    func()
except AttributeError:
    print("dostuff not found")
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Adam Vandenberg
  • 19,991
  • 9
  • 54
  • 56
  • 2
    This link is also having a useful and an important example of the above question https://gist.github.com/hygull/41f94e64b84f96fa01d04567e27eb46b – hygull Dec 31 '17 at 01:56
  • Works well for a call but didn't find the way for assigning a value to the method. Eg: `obj."dostuff" = x` – Abpostman1 Apr 28 '22 at 13:29
  • Answering to myself : Didn't know either SETATTR. So `func = setattr(obj, "dostuff", x)` will do the job – Abpostman1 Apr 28 '22 at 13:40