没有eval的Python变量变量?

时间:2012-08-24 14:29:16

标签: python variables eval variable-variables

有没有办法在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())")

1 个答案:

答案 0 :(得分:10)

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

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