[Zope] PHP style variable variables in Python?

Dieter Maurer dieter@handshake.de
Wed, 10 Apr 2002 20:36:10 +0200


Michael LaPera writes:
 > I am creating a simple Python script that displays a random image 
 > (image1, image2, image3....).
 > All I want to do do is generate a random number which is concatenated to 
 > the end of the context attribute similar to this example in PHP:
 > 
 > $randomNumber = ***some random number***
 > return context.{'image'.$randomNumber}
 > 
 > Is this possible (and easy) in Python?
It is.

It does not use special syntax but a built in function: "getattr".

It looks like:

   return getattr(context,'image' + `randomNumber`)

"+" is concatenation for strings and "`...`" is string representation.


Dieter