iterate over class variables

Y

Yves Glodt

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'

test = testclass()



Then I wanna do sonmething like this:

for name,value in test:
print name
print value

fails with of course with:
"TypeError: iteration over non-sequence"


How can I do that?

regards,
Yves
 
D

Daniel Evers

Hi!

You can iterate over the internal dictionary:
.... def __init__(self):
.... self.x = 5
.... self.y = 6
.... self.z = "Hallo"
.... .... print key
.... print value
....
y
6
x
5
z
Hallo
Consider using iteritems() instead of items() when you have a loop.

Hope that helps :)
Daniel
 
P

Peter Hansen

Yves said:
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'

Is the following of any help to you?
.... a = 'a'
....
>>> dir(testclass) ['__doc__', '__module__', 'a']
>>> testclass.__dict__ {'a': 'a', '__module__': '__main__', '__doc__': None}
>>> import inspect
>>> inspect.classify_class_attrs(testclass)
[('__doc__', 'data', <class __main__.testclass at 0x00AFBE70>, None),
('__module
__', 'data', <class __main__.testclass at 0x00AFBE70>, '__main__'),
('a', 'data'
, <class __main__.testclass at 0x00AFBE70>, 'a')]


There are other methods in "inspect" which could help you.

-Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top