简体   繁体   中英

Iterate over unknown object attributes in Python

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]

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

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM