looping over a class attribute

Dave Benjamin ramen at lackingtalent.com
Mon Mar 15 17:08:08 CET 2004

In article <b82e5469.0403121359.f099aa8 at posting.google.com>, biner wrote:
> I would like to be able to make a loop like this 
>>>> dir(x)
> ['__doc__', '__module__', 'val1', 'val2']
>>>> for i in dir(x) : print x.i

Like Aahz said, getattr(x, i) is your ticket. However, keep in mind that the
behavior of dir() is not guaranteed across current and future versions of
Python. You may have better luck using x.__dict__.keys() - or in Python 2.3,
you can get away with this:

for i in x.__dict__: print getattr(x, i)

Since dictionaries are their own key-iterators now.

.:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
:  please talk to your son or daughter about parametric polymorphism. :

More information about the Python-list mailing list