Python code refactoring issue. simplification

I have some 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 it is obvious that the presence of variables in the list without the "self.ui" part is invalid, and I would prefer not to enter "self.ui" for each element in the list, because it really is not much better. How can I rewrite my first code to make it something like what I'm talking about?

+3
source share
2 answers

Here's how you do it:

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

items There should be a list of lines.

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

Source: https://habr.com/ru/post/1752325/


All Articles