Python variable variables without eval?

2020-04-12 09:53发布

Is there is a way to access variables using a variable string in python? For instance, I would like a neater way than using eval for the following:

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

1条回答
欢心
2楼-- · 2020-04-12 10:18

What you're looking for is the getattr() built-in function. There is also hasattr() and setattr().

button = getattr(self, 'flipButton')
button.setEnabled(True)
查看更多
登录 后发表回答