在python中循环一个类的所有成员变量 [英] looping over all member variables of a class in python
本文介绍了在python中循环一个类的所有成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取可迭代类中所有变量的列表?有点像 locals(),但对于一个类
class 示例(对象):bool143 = 真bool2 = 真废话=假foo = 真foobar2000 = 假def as_list(self)ret = []对于 XXX 中的字段:如果 getattr(self, field):ret.append(字段)返回 ",".join(ret)
这应该返回
<预><代码>>>>e = 示例()>>>e.as_list()bool143, bool2, foo 解决方案
dir(obj)
为您提供对象的所有属性.您需要自己从方法等中过滤掉成员:
class 示例(对象):bool143 = 真bool2 = 真废话=假foo = 真foobar2000 = 假示例 = 示例()members = [attr for attr in dir(example) if not callable(getattr(example, attr)) 而不是 attr.startswith("__")]印刷会员
会给你:
['blah', 'bool143', 'bool2', 'foo', 'foobar2000']
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
解决方案
dir(obj)
gives you all attributes of the object. You need to filter out the members from methods etc yourself:
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
Will give you:
['blah', 'bool143', 'bool2', 'foo', 'foobar2000']
这篇关于在python中循环一个类的所有成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文