Frage

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())")
War es hilfreich?

Lösung

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

button = getattr(self, 'flipButton')
button.setEnabled(True)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top