2

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())")
Hooked
  • 84,485
  • 43
  • 192
  • 261
Ben
  • 885
  • 1
  • 12
  • 25

1 Answers1

10

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

button = getattr(self, 'flipButton')
button.setEnabled(True)
Fabian
  • 4,160
  • 20
  • 32