Reputation:
I have this class definition:
class cols:
name = 'name'
size = 'size'
date = 'date'
@classmethod
def foo(cls):
print "This is a class method"
With __dict__ I get all class attributes (members and variables). Also there are the "Internal attributes" too (like __main__). How can I get only the class variables without instantiation?
Upvotes: 4
Views: 1456
Reputation: 86512
I wouldn't know a straightforward way, especially since from the interpreter's POV, there is not that much of a difference between a method of a class and any other variable (methods have descriptors, but that's it...).
So when you only want non-callable class members, you have to fiddle around a little:
>>> class cols:
... name = "name"
... @classmethod
... def foo(cls): pass
>>> import inspect
>>> def get_vars(cls):
... return [name for name, obj in cls.__dict__.iteritems()
if not name.startswith("__") and not inspect.isroutine(obj)]
>>> get_vars(cols)
['name']
Upvotes: 5
Reputation: 18431
import inspect
inspect.getmembers(cols)
There are a lot if things you can do with the inspect module: http://lfw.org/python/inspect.html
Upvotes: 1