4

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?

Har
  • 3,727
  • 10
  • 41
  • 75
  • 1
    All of the methods listed below will work for your example case, but would also list any methods or properties you have defined (since, from Python's prospective, they're the all the same thing, names of attributes of a class). If that is not the behavior you want, you should edit the question to be more clear. You should also edit your code to accurately reflect what you're running, because your example of what you tried 1) isn't valid python, 2) even if it was, wouldn't generate your error condition. – aruisdante Feb 24 '15 at 00:06
  • yes you are right, I have updated the code and the description, the python code I provided was incorrect. – Har Feb 24 '15 at 10:03

2 Answers2

6
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)]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    Note this won't work if you have an *instance* of myclass (which I'm guessing the OP does since they're getting `myvar`, which you wouldn't from `dir(myclass)`). You'd need `dir(type(instance))` instead. – aruisdante Feb 23 '15 at 23:56
  • Absolutely. So their error condition don't match their code. Suggesting their code is wrong, or their error condition is. – aruisdante Feb 24 '15 at 00:00
  • Thanks guys, this is what I wanted, the only question left is answering whether or not it is an instance or a class as you also mentioned that dir(mylcass) (for class case) and dir(type(mylcass)) (for instance case) would work – Har Feb 24 '15 at 10:07
2

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)]
Maciej Gol
  • 15,394
  • 4
  • 33
  • 51
  • Thanks I think the inspect module is something worth knowing especially the inspect.isclass(X) can be used to determine whether or not a class is an instance or an actual type – Har Feb 24 '15 at 10:21