Python Class iteration howto !

Michal Wallace sabren at manifestation.com
Sat Sep 9 16:33:18 CEST 2000


On Sat, 9 Sep 2000, Sindh wrote:

> class xyz:
> 	name=''
> 	age=0
> 	sex='U'
> 	address='U'
> 
> def iter(a):
> 	for n in dir(a):
> 		print a.n
> 
> but the above code says no attribute called a.n. How do I tell python to
> substitute n for a attrib from list.

You get the error because "a.n" is a completely different variable
than "n"... "a" is its own namespace. To do this kind of dynamic
stuff, you either need a little routine called getattr(), direct
access to a.__dict__, or to use exec/eval.... despite what they tell
you, ThereIsMoreThanOneWayToDoIt.. :)


Cheers,

- Michal
------------------------------------------------------------------------
www.manifestation.com  www.sabren.com  www.linkwatcher.com  www.zike.net
------------------------------------------------------------------------





More information about the Python-list mailing list