dynamically created names / simple problem

John Nagle nagle at animats.com
Tue Mar 25 20:54:54 EDT 2008


Robert Bossy wrote:
> Jules Stevenson wrote:
>>
>> Hello all,
>>
>> I'm fairly green to python and programming, so please go gently. The 
>> following code
>>
>> for display in secondary:
>>
>> self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, 
>> "checkbox_2")
>>
>> Errors, because of the apparent nastyness at the beginning. What I’m 
>> trying to do is loop through a list and create uniquely named wx 
>> widgets based on the list values. Obviously the above doesn’t work, 
>> and is probably naughty – what’s a good approach for achieving this?
>>
> Hi,
> 
> What you're looking for is the builtin function setattr:
> http://docs.python.org/lib/built-in-funcs.html#l2h-66

     Actually, you don't need to use attributes for this at all.
You're better off with an ordinary dictionary.  Something like this:

     	class someclass(object) :
	    def __init__(self) :
	        self.widgets = {} # empty dictionary

	    def addwidget(self, widgetname, widgetfn)
	        self.widgets[widgetname] = widgetfn

	    def callwidgetbyname(self, widgetname, args)
	        self.widgets[widgetname](*args)

The only reason to use attributes is when you want to allow the
use of the notation

	objectinstance.attributename

If you're only going to get the attributes with getattr, they
don't need to be attributes.

				John Nagle



More information about the Python-list mailing list