calling a method using a variable name?
jeremy at zope.com
Fri Mar 14 22:36:18 CET 2003
On Fri, 2003-03-14 at 16:20, Alan McIntyre wrote:
> How about this:
> myMethod = 'method'
> myCall = 'z=X.'+myMethod+'()'
> 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)
More information about the Python-list