Re: [Beginner] Calling a function by its name in a string
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

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

From: Paul Rubin <//phr.cx@NOSPAM.invalid>
Date: Wed Jul 27 2005 - 21:02:41 CEST

Tito <titogarcia_borra_esto@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)
Received on Thu Sep 29 17:11:56 2005