wewa
wewa

Reputation: 1678

Iterate of a Class´ attributes

there exists following class.

class Reaction(object):
    Var1 = "lorem"
    Var2 = "impsum"
    Var3 = "dolor"

I'd like to iterate over the attributes of this class, like in following code.

for value in Reaction:
    print value

This should produce following output.

lorem
ipsum
dolor

I've already found this topic: How to iterate over a the attributes of a class, in the order they were defined?, but it doesn't really help me.

How can I make my class iterable?

EDIT: I thought of something similar like in this post: Build a Basic Python Iterator.

Upvotes: 0

Views: 342

Answers (3)

Otto Allmendinger
Otto Allmendinger

Reputation: 28288

First off, what you are trying is a little unusual - normally, a dict is used for this kind of thing

Reaction = {
   var1: "Lorem",
   var2: "Ipsum",
   var3: "Dolor"
}

If for some reason you still prefer your method, you can use inspect.getmembers(). A helper function could look like this

def attributes(class_):
    for name, value in inspect.getmembers(class_):
        if not name.startswith("__"):
             yield name, value

Then you can do

for name, value in attributes(Reactor):
    # do stuff

Upvotes: 1

applicative_functor
applicative_functor

Reputation: 4986

>>> for k, v in Reaction.__dict__.iteritems():
...     if not k.startswith('__'):
...         print v
... 
lorem
dolor
impsum

Or better:

>>> import inspect
>>> class Reaction(object):
...     Var1 = "lorem"
...     Var2 = "impsum"
...     Var3 = "dolor"
...     def __iter__(self):
...         return (v for k, v in inspect.getmembers(self) if not k.startswith('__'))
... 
>>> for value in Reaction():
...     print value
... 
lorem
impsum
dolor

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 600026

If you really need an object whose members are accessible via dot notation but you still want to iterate through them, you need a namedtuple.

Reaction = collections.namedtuple('Reaction', ['Var1', 'Var2', 'Var3'])
reaction = Reaction('lorem', 'ipsum', 'dolor')
for value in reaction:
    print value

Upvotes: 3

Related Questions