"Variable variable name" or "variable lvalue"

Francesco Guerrieri f.guerrieri at gmail.com
Wed Aug 15 16:54:39 EDT 2007


On 8/15/07, mfglinux <mfglinux at gmail.com> wrote:
>
>
> #Let's say x=3, then Period definition is
> Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a
> python class
>
> I dont know how to automatize last piece of code for any x
>



Hello,

you could use exec to create on the fly the variables as you need them (but
be aware that the use of exec can be dangerous and is probably not needed),
or you could add the proper name to a relevant dictionary (for example,
locals() ). Something like

for counter in xrange(3):
    locals()["Material" + str(counter)] = Material(12.5)


But if you need the variables only for calling Slab, you could write
something like:

material_number = 3
material_list = [Material(12.5) for x in xrange(0, counter)]
Period = Slab(sum(material_list))

bye,
francesco
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070815/b9a54104/attachment.html>


More information about the Python-list mailing list