iterate over class variables

bruno at modulix onurb at xiludom.gro
Thu Nov 10 07:42:18 EST 2005


Yves Glodt wrote:
> Yves Glodt wrote:
> 
>> Hello list,
>>
>> I need to iterate over a class and get all her variable names and
>> values, e.g. considering this example:
>>
>>
>> class testclass:
>>     var1 = 'ab'
>>     var2 = 'cd'
>>     var3 = 'ef'

Take care, these are *class* variables, not instance variables.

>> test = testclass()
>>
>> Then I wanna do sonmething like this:
>>
>> for name,value in test:
>>     print name
>>     print value
>>
(snip)
>
> sorry for selfreplying, but I found a solution:
> 
> for key in dir(test):
>     if '__' not in key:
>         value = getattr(test,key)
>         print key, value
> 
> Does anything speak about this?

1/ dir() doesn't necessary returns all the attributes of an object:
"""
dir(...)
    dir([object]) -> list of strings

    Return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it:
"""

But I don't think this is a problem here.

2/ everything being an object, dir() also returns methods (a method
being a - callable - attribute of the object's class).

If you're only interested in data attributes, you may want to try this:

for key in dir(test):
    if not key.startswith('__'):
        value = getattr(test,key)
        if not callable(value):
            print key, value


You can also check inspect.getmember()

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list