在python中遍历一个类的所有成员变量


问题内容

如何获得可迭代类中所有变量的列表?有点像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)

这应该返回

>>> e = Example()
>>> e.as_list()
bool143, bool2, foo

问题答案:
dir(obj)

为您提供对象的所有属性。您需要自己从方法等中过滤出成员:

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

example = Example()
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print members

会给你:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']