Iterate creating variables?

Mark Tolonen M8R-yfto6h at mailinator.com
Mon Jun 16 10:02:31 EDT 2008


"Hyuga" <hyugaricdeau at gmail.com> wrote in message 
news:f9b72959-8c81-4e26-84e6-c80b1c84c4b2 at 34g2000hsh.googlegroups.com...
> On Jun 13, 11:34 am, "Reedick, Andrew" <jr9... at ATT.COM> wrote:
>> > -----Original Message-----
>> > From: python-list-bounces+jr9445=att.... at python.org [mailto:python-
>> > list-bounces+jr9445=att.... at python.org] On Behalf Of tda... at gmail.com
>> > Sent: Friday, June 13, 2008 11:11 AM
>> > To: python-l... at python.org
>> > Subject: Iterate creating variables?
>>
>> > I have twenty-five checkboxes I need to create (don't ask):
>>
>> > self.checkbox1 = ...
>> > self.checkbox2 = ...
>> > .
>> > .
>> > .
>> > self.checkbox25 = ...
>>
>> > Right now, my code has 25 lines in it, one for each checkbox, since
>> > these are all variables.
>>
>> > Is there a way to write a loop so that I can have fewer lines of code
>> > but still keep the variables?
>>
>> > I've tried:
>>
>> > for o in xrange(25):
>> >     self.checkbox[o] = ...
>>
>> > which didn't work, and
>>
>> > for o in xrange(25):
>> >     self.checkbox[''%d'%(o)] = ...
>>
>> > which also didn't work.
>>
>> > Both give the error message: "Attribute error: Main.App has no
>> > attribute "checkbox"", which clearly indicates that I'm not keeping
>> > the "variability" aspect I want.
>>
>> > Is there a way?
>>
>> > I appreciate any and all answers!
>>
>> Either store the checkboxes in an array or hash/dictionary.  If that's
>> not practical, then
>> You can use strings to build the code and use eval to execute the string
>> as code.  Ex:
>>
>> for i in range(10):
>>         code = "%d + %d" % (i, i)
>>         print eval(code)
>
> Don't do this.  You want
>
> for idx in range(10):
>    setattr(self, 'checkbox_%i' % idx)

Assuming create_checkbox() is the function to create a checkbox, this will 
create a list of 25 checkboxes::

    checkbox = [create_checkbox() for i in xrange(25)]

--Mark




More information about the Python-list mailing list