没有 eval 的 Python 变量变量?

Python variable variables without eval?

提问人:Ben 提问时间:8/24/2012 最后编辑:HookedBen 更新时间:10/18/2020 访问量:866

问:

有没有办法在 python 中使用变量字符串访问变量?例如,我想要一种更整洁的方式,而不是用于以下内容:eval

def toggleListButtons (self):
    buttons = ["flip", "remove", "removeAll", "delete", "deleteAll", "loadDirectory"]
    for button in buttons:
        eval("self." + button + "Button.setEnabled(!self." + button + "Button.isEnabled())")
python 变量 eval 变量

评论

1赞 msw 8/24/2012
+1 好问题,因为 Eval 是邪恶的
1赞 msw 8/24/2012
有多邪恶?非常。stackoverflow.com/questions/1832940/......

答:

10赞 Fabian 8/24/2012 #1

你要找的是getattr()内置函数。还有 hasattr()setattr()。

button = getattr(self, 'flipButton')
button.setEnabled(True)