开发者

Python code refactoring question. Applying functions to multiple elements

开发者 https://www.devze.com 2023-01-05 11:21 出处:网络
I have code that looks something like this: self.ui.foo.setEnabled(False) self.ui.bar.setEnabled(False)

I have code that looks something like this:

self.ui.foo.setEnabled(False)
self.ui.bar.setEnabled(False)
self.ui.item.setEnabled(False)
self.ui.item2.setEnabled(False)
self.ui.item3.setEnabled(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.setEnabled(False)

But obviously just having the variables in the list with out the 'self.ui' part is invalid, and I would rather not开发者_如何学C 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?


Grab the object to have the function called on it by its attribute name using the built-in getattr function:

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


You could try something like:

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

精彩评论

暂无评论...
验证码 换一张
取 消