1

I have a class as such below. However, the attribute names remain unknown. How, under this circumstance, do a make a class iterator? Basic examples point to __iter__ and next() having some knowledge of the class's attributes as does the example in the pydocs.

class Foo(object):
    def __init__(self, dictionary):
        for k, v in dictionary.iteritems():
            setattr(self, k, v)

I would like to iterate through each object attribute something like so:

bar = Foo(dict)
for i in bar:
    bar[i]

2 Answers 2

3

As @TheSoundDefense suggested you can use the vars() built-in to list all the attributes of the object. The following answer extends the idea with an example of using it in your case

Implementation

class Foo(object):
    def __init__(self, dictionary):
        for k, v in dictionary.iteritems():
            setattr(self, k, v)
    def __iter__(self):
        return iter(vars(self))

Demo

foo = Foo({'X':1, 'Y':2, 'Z':3})
for elem in foo:
    print elem

Output

Y
X
Z
Sign up to request clarification or add additional context in comments.

1 Comment

And I am defeated by an overlong lunch. Good answer.
3

You may want the vars() function here. That will return a dictionary of attribute names and values for any arbitrary object. Just use vars(obj_name).

2 Comments

Are you suggesting to use vars() with the class as part of making the it iterable?
Yes, to generate the initial dictionary. Then you could iterate over them how you like, probably with iteritems. Mainly I was addressing how to obtain the attributes if the names are unknown. I'll post an update when I get back from lunch, unless a better answer comes along.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.