简体   繁体   English

Python代码重构问题。 将功能应用于多个元素

[英]Python code refactoring question. Applying functions to multiple elements

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 type out 'self.ui' for every element in the list, because that really isn't to much better. 但是显然,仅在列表中包含“ self.ui”部分的变量是无效的,并且我宁愿不要为列表中的每个元素都键入“ self.ui”,因为这实际上并没有更好。 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: 使用内置的getattr函数,使对象具有通过其属性名称调用的函数:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM