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

Paul Rubin http
Wed Jul 27 15:02:41 EDT 2005


Tito <titogarcia_borra_esto at gmail.com> writes:
> def printPropertyForEach(collection, propertyName):
>    for elem in collection:
>      print eval("elem." + propertyName)
> 
> Is there another approach to do it?

Yes, use the getattr function:

   for elem in collection:
     print getattr(elem, propertyName)



More information about the Python-list mailing list