Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I have a class as follows:

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

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

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

like image 830
Har Avatar asked Mar 17 '23 22:03

Har


2 Answers

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)]
like image 82
Padraic Cunningham Avatar answered Apr 27 '23 21:04

Padraic Cunningham


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)]
like image 27
Maciej Gol Avatar answered Apr 27 '23 19:04

Maciej Gol