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())")
2
  • 1
    +1 good question because eval is evil Commented Aug 24, 2012 at 14:31
  • 1
    how evil? very. stackoverflow.com/questions/1832940/… Commented Aug 24, 2012 at 14:38

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.