Python 2.7: How to get the list of static variables in a class?

前端 未结 2 1776
梦谈多话
梦谈多话 2021-01-19 05:52

If I have a class as follows:

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

相关标签:
2条回答
  • 2021-01-19 06:22
    print([ getattr(myclass,x) for x in dir(myclass) if not x.startswith("__")])
    [20, 30, 40]
    

    Or:

    print([v for k,v in myclass.__dict__.items() if not k.startswith("__")])
    

    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)]
    

    Using dict:

    [v for k,v in myclass.__dict__.items() if isinstance(v,int)]
    
    0 讨论(0)
  • 2021-01-19 06:29

    You can also use the inspect module:

    >>> [x for x in inspect.getmembers(myclass) if not x[0].startswith('__')]
    [('i', 20), ('j', 30), ('k', 40)]
    
    0 讨论(0)
提交回复
热议问题