calling a method using a variable name?

Jeremy Hylton jeremy at zope.com
Fri Mar 14 16:36:18 EST 2003


On Fri, 2003-03-14 at 16:20, Alan McIntyre wrote:
> How about this:
> 
> myMethod = 'method'
> myCall = 'z=X.'+myMethod+'()'
> exec(myCall)
> 
> Patrick Price wrote:
>  >
>  > Can I call a method of a class using a variable, eg:
>  >
>  > class X:
>  >   def method():
>  >      pass
>  >
>  >
>  > z=X."method"()
>  >
>  > How would I do this?  I need to call different methods (read from a
>  > list) without hardcoding them in the program.
>  >

Actually, you should use getattr() instead of exec.

def callMethod(obj, methname, *args, **kwargs):
    meth = getattr(obj, methname)
    return meth(*args, **kwargs)

Jeremy








More information about the Python-list mailing list