views:

97

answers:

2

I have code that looks something like this:

self.ui.foo = False
self.ui.bar = False
self.ui.item = False
self.ui.item2 = False 
self.ui.item3 = False

And I would like to turn it into something like this:

items = [foo,bar,item,item2,item3]
for elm in items:
    self.ui.elm = False

But obviously just having the variables in the list with out the 'self.ui' part is invalid, and I would rather not type out 'self.ui' for every element in the list, because that really isn't to much better. How could I rewrite my first code to make it something like what I'm talking about?

+6  A: 

Here's how you do that:

items = ['foo','bar','item','item2','item3']
for elm in items:
    setattr(self.ui, elm, False)
David Zaslavsky
+4  A: 

items needs to be a list of strings.

items = ['foo', 'bar', 'item', 'item2', 'item3']
for elm in items:
    setattr(self.ui, elm, False)
Nikhil Chelliah