本文介绍了没有eval的Python变量变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用python中的变量字符串访问变量?例如,我想要一种更整洁的方式,而不是对以下内容使用eval:

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())")

推荐答案

您正在寻找的是 getattr()内置函数.还有 hasattr() setattr().

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

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

这篇关于没有eval的Python变量变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:22