在Python中遍历类的所有成员变量

138 投票
8 回答
164887 浏览
提问于 2025-04-15 14:10

你怎么能得到一个可以遍历的类里面所有变量的列表呢?就像使用 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

8 个回答

33

@truppo:你的回答差不多是对的,但 callable 总是会返回 false,因为你只是传入了一个字符串。你需要像下面这样:

[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")]

这样就能过滤掉函数了。

159

如果你只想要变量(不包括函数),可以使用:

vars(your_object)
210
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']

撰写回答