Interesting problem - can it be done

Erik Max Francis max at
Thu Aug 9 08:14:36 CEST 2001

Mark Sass wrote:

>     I have a list of strings and the strings are functions that I want
> to
> call on an object.

So you mean methods.

> How do I call the functions without hardcoding the
> function call?  Here is an example
> funclist = ['func1()', 'func2()', 'func3()']
> x = len(funclist)
> y = 0
> while y < x:
>     value = testobj.funclist[y]
>     y = y +1

What you want is the getattr function, which takes an object and a
string representing an attribute name (but with no parentheses).  You
can then call that.

Another obvious thing missing is the for idiom, which iterates over
list.  This means you can avoid the while loops and the iteration

	methods = ['method1', 'method2', 'method3']
	for method in methods:
	    value = apply(getattr(testobj, method), ())

getattr turns the instance and the string attribute name into a bound
object, then apply calls it.  The () is the tuple of arguments, which in
this case is empty.

 Erik Max Francis / max at /
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Love is like war:  easy to begin but very hard to stop.
\__/ H.L. Mencken
    Maths reference /
 A mathematics reference.

More information about the Python-list mailing list