反復可能なクラス内のすべての変数のリストを取得するにはどうすればよいでしょうか?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
ベストアンサー1
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']