looping over all member variables of a class in python

How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class

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)

this should return

>>> e = Example()
>>> e.as_list()
bool143, bool2, foo
134690 次浏览
>>> 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']

如您所见,它提供了 所有属性,所以您需要过滤掉一些。但基本上,dir()就是你要找的。

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

The easy way to do this is to save all instances of the class in a 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

@ truppo: 您的答案几乎是正确的,但是 callable 总是返回 false,因为您只是传递了一个字符串。你需要这样的东西:

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

它会过滤掉函数

如果只需要变量(不需要函数) ,请使用:

vars(your_object)
row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns} if r else {}

用这个。

类似于 vars(),我们可以使用下面的代码来列出所有的类属性。

example.__dict__.keys()
ClassName.__dict__["__doc__"]

This will filter out functions, in-built variables etc. and give you just the fields that you need!