Dynamic variables

Michal Wallace sabren at manifestation.com
Mon Jul 31 16:03:38 EDT 2000


On Mon, 31 Jul 2000, Daley, Mark W wrote:

> Does anyone know of a way to create variables on the fly, like in a
> loop?  I want to be able to build a set of check buttons in a GUI
> I'm writing, and each check button needs a different variable, I
> think, to determine which ones are checked.  I want to use a for
> loop to iterate over a list to build the check buttons, but I don't
> know the contents or length of the list.  Any ideas?
 

The concept is called anonymous objects. In python, objects can have
more than one reference pointing to them. Some of those references
have names, or labels that you can see in the code. eg:

>>> x = SomeClass()

.. That creates a SomeClass instance and calls it "x". But
you can then say:

>>> y = [x]

.. And now y[0] references the same SomeClass instance. 
if you then say:

>>> x = None

.. y[0] is STILL REFERENCING the original SomeClass instance. 
It's just "anonymous" now because it doesn't have a specific
name. You could just as easily have said:

>>> y = [SomeClass()]

and if you want more than one:

>>> y = []
>>> for x in range(10):
...     y.append[SomeClass()]


Here's some psuedocode that might get you thinking:

>>> btnLst = []
>>> for x in range(whatever):
...    newBtn = SomeButton() # just create the widget
...    btnValue =  SomeValue() # read from a list, maybe?
...    newBtn.pack() # or whatever to get it on the screen
...    list.append((newBtn,btnValue)


and later on:

>>> for button in btnLst:
...     if button.isChecked:
...         DoWhatever()


Cheers,

- Michal
------------------------------------------------------------------------
www.manifestation.com  www.sabren.com  www.linkwatcher.com  www.zike.net
------------------------------------------------------------------------





More information about the Python-list mailing list