iterate over class variables

Yves Glodt y.glodt at sitasoftware.lu
Thu Nov 10 08:41:24 EST 2005


bruno at modulix wrote:
> 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

This serves me well so far, thanks to you, Peter and Daniel for the 
suggestions!

Yves (still amazed of the responsiveness of this list :-)


> You can also check inspect.getmember()



More information about the Python-list mailing list