【问题标题】:Python variable variables without eval?没有eval的Python变量变量?
【发布时间】:2012-08-20 03:12:14
【问题描述】:

有没有办法在 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 variables eval variable-variables


【解决方案1】:

您正在寻找的是getattr() 内置函数。还有hasattr()setattr()

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

【讨论】:

    猜你喜欢
    • 2018-12-02
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多