Python 2.7:如何获取类中的静态变量列表? [英] Python 2.7: How to get the list of static variables in a class?

查看:53
本文介绍了Python 2.7:如何获取类中的静态变量列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类如下:

class myclass(object):
    i = 20
    j = 30
    k = 40
    def __init__(self):
        self.myvariable = 50

如何获取包含 i、j 和 k 的列表?(类的静态成员)我曾尝试使用:

How can I get the list which contains i, j and k? (static members of the class) I have tried to use the:

[x for x in dir(a) if isinstance(getattr(a, x), (int, long))]

然而,这也会返回 self.myvariable.有没有办法在实例和类类型上执行此操作?

however that also returns the self.myvariable. Is there a way to perform this on an instance aswell as a class type?

推荐答案

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:

If you are trying to use check the type it is issinstance:

[getattr(myclass, x) for x in dir(myclass) if isinstance(getattr(myclass, x) , int)]

使用字典:

[v for k,v in myclass.__dict__.items() if isinstance(v,int)]

这篇关于Python 2.7:如何获取类中的静态变量列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆