looping over all member variables of a class in python

@truppo: your answer is almost correct, but callable will always return false since you're just passing in a string. You need something like the following:

[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")]

which will filter out functions


If you want only the variables (without functions) use:

vars(your_object)

dir(obj)

gives you all attributes of the object. You need to filter out the members from methods etc yourself:

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

example = Example()
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print members   

Will give you:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']

Tags:

Python