循环遍历python中类的所有成员变量

pri*_*stc 79 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)
Run Code Online (Sandbox Code Playgroud)

这应该回来了

>>> e = Example()
>>> e.as_list()
bool143, bool2, foo
Run Code Online (Sandbox Code Playgroud)

tru*_*ppo 130

dir(obj)
Run Code Online (Sandbox Code Playgroud)

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

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   
Run Code Online (Sandbox Code Playgroud)

会给你:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']
Run Code Online (Sandbox Code Playgroud)

  • `callable(attr)`如何工作?不是`attr`是一个字符串? (8认同)
  • 为什么实例化一个对象:dir(Example())而不仅仅是类类型dir(例子) (7认同)
  • 你如何获得价值? (7认同)
  • @knutole:getattr(object,attr) (6认同)
  • 你应该使用`vars(例子).items()`或`vars(instance .__ class __).items()`而不是`dir()`如果你想检查它是否可以调用,因为dir只会返回' `string`s作为名字.. (5认同)
  • 因为我猜 OP 正在寻找实例变量(可能不存在于类中)。 (2认同)

Nim*_*imo 100

如果只想要变量(没有函数),请使用:

vars(your_object)
Run Code Online (Sandbox Code Playgroud)

  • 你仍然需要过滤__vars__但这是正确的答案 (5认同)
  • `vars`不*包含类变量,只包含实例变量. (5认同)
  • 真的很喜欢这种方法用它来找出在通过网络发送状态之前序列化的内容,例如... (2认同)
  • @DilithiumMatrix 您需要在类本身上使用 vars(THECLASSITSELF) 来获取类变量。在下面检查我的答案。 (2认同)
  • 使用此方法来具体回答OP的问题:`members = list(vars(example).keys())` as(至少在python3中)`vars`返回一个`dict`,将成员变量的名称映射到它的值。 (2认同)

use*_*925 26

@truppo:你的答案几乎是正确的,但是callable总是返回false,因为你只是传入一个字符串.您需要以下内容:

[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")]
Run Code Online (Sandbox Code Playgroud)

这将过滤掉功能


bal*_*pha 6

>>> a = Example()
>>> dir(a)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'bool143', 'bool2', 'blah',
'foo', 'foobar2000', 'as_list']
Run Code Online (Sandbox Code Playgroud)

- 如你所见,它为你提供了所有属性,所以你必须过滤掉一点.但基本上,dir()就是你要找的东西.