Iterate creating variables?

Diez B. Roggisch deets at nospam.web.de
Fri Jun 13 11:21:03 EDT 2008


tdahsu at gmail.com schrieb:
> 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?

Keep either a list or dictionary around. Like this:

checkboxes = []

for o in xrange(25):
     checkboxes.append(....create a checkbox...)

self.checkboxes = checkboxes

Diez



More information about the Python-list mailing list