[Beginner] Calling a function by its name in a string

Bill Mill bill.mill at gmail.com
Wed Jul 27 15:04:24 EDT 2005


On 7/27/05, Tito <titogarcia_borra_esto at gmail.com> wrote:
> Thank you both for your quick answers.
> 
> What I wanted is to parameterize a function with another member
> function, like this:
> 
> def printFunctionForEach(collection, functionName):
>    for elem in collection:
>      print eval("elem." + functionName + "()")
> 
> Moreover, I wanted to do it with a property:
> 
> def printPropertyForEach(collection, propertyName):
>    for elem in collection:
>      print eval("elem." + propertyName)
> 
> Is there another approach to do it?
> 

Sure, piece of cake:

>>> class test:
...     def func1(self): print 'func1 called'
...
>>> class test2:
...     def func1(self): print 'other func1'
...
>>> x = [test(), test2(), test()]
>>> def call_this_func(lst, func_name):
...     for e in lst:
...         getattr(e, func_name)()
...
>>> call_this_func(x, 'func1')
func1 called
other func1
func1 called
>>>

Note that the getattr raises an AttributeError if func_name doesn't
exist in the object; you should probably wrap it in a try/except.

Peace
Bill Mill
bill.mill at gmail.com



More information about the Python-list mailing list