如果我有如下课程:
class myclass(object):
i = 20
j = 30
k = 40
def __init__(self):
self.myvariable = 50
如何获取包含i,j和k的列表? (班级的静态成员) 我试图使用:
[x for x in dir(a) if isinstance(getattr(a, x), (int, long))]
然而,这也返回self.myvariable。有没有办法在实例和类类型上执行此操作?
答案 0 :(得分:5)
print([ getattr(myclass,x) for x in dir(myclass) if not x.startswith("__")])
[20, 30, 40]
或者:
print([v for k,v in myclass.__dict__.items() if not k.startswith("__")])
如果您尝试使用检查类型issinstance
:
[getattr(myclass, x) for x in dir(myclass) if isinstance(getattr(myclass, x) , int)]
使用dict:
[v for k,v in myclass.__dict__.items() if isinstance(v,int)]
答案 1 :(得分:2)
您还可以使用inspect
模块:
>>> [x for x in inspect.getmembers(myclass) if not x[0].startswith('__')]
[('i', 20), ('j', 30), ('k', 40)]