Python Class iteration howto !

Piet van Oostrum piet at cs.uu.nl
Sat Sep 9 07:26:50 EDT 2000


>>>>> Sindh <skodela at my-deja.com> (S) writes:

S> Hi all
S> Suppose I have a class xyz with attributed name,age,sex,address etc. How
S> do I iterate the values.

S> eg:

S> class xyz:
S> 	name=''
S> 	age=0
S> 	sex='U'
S> 	address='U'

S> def iter(a):
S> 	for n in dir(a):
S> 		print a.n

S> but the above code says no attribute called a.n. How do I tell python to
S> substitute n for a attrib from list.

class xyz:
    def __init__(self):
        self.name='Piet'
        self.age=0
        self.sex='U'
        self.address='U

def iter(a):
    for n in dir(a):
        print a.__dict__[n]
# or    print getattr(a,n)


u=xyz()
iter(u)

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl



More information about the Python-list mailing list