如何获得可迭代的类中的所有变量的列表?有点像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)
Nim*_*imo 100
如果只想要变量(没有函数),请使用:
vars(your_object)
Run Code Online (Sandbox Code Playgroud)
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)
这将过滤掉功能
>>> 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()就是你要找的东西.
| 归档时间: |
|
| 查看次数: |
71534 次 |
| 最近记录: |