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

问题描述 投票:0回答:9

如何获取可迭代类中所有变量的列表?有点像 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
python
9个回答
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']

160
投票

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

vars(your_object)

33
投票

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

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

这将过滤掉函数


7
投票
>>> 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']

— 如您所见,这为您提供了 all 属性,因此您必须过滤掉一些属性。但基本上,

dir()
就是您要寻找的。


2
投票

vars()
类似,可以使用下面的代码列出所有类属性。相当于
vars(example).keys()

example.__dict__.keys()

0
投票

灵感来自https://stackoverflow.com/a/13286863/14298786

class CONSTANT:
    a = 4
    b = 5

    def display() -> None:
        print("Hello!")


print(vars(CONSTANT))
# {'__module__': '__main__', 'a': 4, 'b': 5, 'display': <function CONSTANT.display at 0x1030bcb80>, '__dict__': <attribute '__dict__' of 'CONSTANT' objects>, '__weakref__': <attribute '__weakref__' of 'CONSTANT' objects>, '__doc__': None}
print(
    [k for k, v in vars(CONSTANT).items() if not callable(v) and not k.startswith("__")]
)
# ['a', 'b']
print(
    {
        k: v
        for k, v in vars(CONSTANT).items()
        if not callable(v) and not k.startswith("__")
    }
)
# {'a': 4, 'b': 5}

-1
投票
row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns} if r else {}

用这个。


-1
投票
ClassName.__dict__["__doc__"]

这将过滤掉函数、内置变量等,并只为您提供所需的字段!


-4
投票

执行此操作的简单方法是将类的所有实例保存在

list
中。

a = Example()
b = Example()
all_examples = [ a, b ]

物体不会自发地产生。程序的某些部分创建它们是有原因的。创造是有原因的。将它们收集在列表中也是有原因的。

如果你使用工厂,你可以这样做。

class ExampleFactory( object ):
    def __init__( self ):
        self.all_examples= []
    def __call__( self, *args, **kw ):
        e = Example( *args, **kw )
        self.all_examples.append( e )
        return e
    def all( self ):
        return all_examples

makeExample= ExampleFactory()
a = makeExample()
b = makeExample()
for i in makeExample.all():
    print i
© www.soinside.com 2019 - 2024. All rights reserved.