如何获得可迭代的类中的所有变量的列表?有点像locals(),但对于一个类
class Example(object):
bool143 = True
bool2 = True
blah = False
foo = True
foobar2000 = False
def as_list(self)
ret = []
for field in XXX:
if getattr(self, field):
ret.append(field)
return ",".join(ret)
Run Code Online (Sandbox Code Playgroud)
这应该回来了
>>> e = Example()
>>> e.as_list()
bool143, bool2, foo
Run Code Online (Sandbox Code Playgroud) 我知道应该避免使用eval()和exec(),但在这种情况下它似乎是最好的选择:我从wxPython中的复选框和文本框中获取值并将它们放入我的配置类中.这是我使用eval()的方式:
config = wx.Config()
checkBoxes = ['option_1', 'option_2']
for key in checkBoxes:
config.Write(key, str(eval('self.m_checkBox_'+key+'.GetValue()'))
Run Code Online (Sandbox Code Playgroud)
没有任何安全问题,因为没有任何用户输入到eval,对我来说似乎很清楚.有一个更好的方法吗?