Dap
Dap

Reputation: 2359

How to iterate over class attributes but not functions and returning the attribute values in python?

Building on this question looping over all member variables of a class in python

Regarding how to iterate over a class' attributes / non functions. I want to loop over the class variable values and store in a list.

class Baz:
    a = 'foo'
    b = 'bar'
    c = 'foobar'
    d = 'fubar'
    e = 'fubaz'

    def __init__(self):
       members = [attr for attr in dir(self) if not attr.startswith("__")]
       print members

   baz = Baz()

Will return ['a', 'b', 'c', 'd', 'e']

I would like the class attribute values in the list.

Upvotes: 3

Views: 5834

Answers (2)

greole
greole

Reputation: 4771

Use the getattr method:

class Baz:
    a = 'foo'
    b = 'bar'
    c = 'foobar'
    d = 'fubar'
    e = 'fubaz'

    def __init__(self):
       members = [getattr(self,attr) for attr in dir(self) if not attr.startswith("__")]
       print members

baz = Baz()
['foo', 'bar', 'foobar', 'fubar', 'fubaz']

Upvotes: 2

Ashoka Lella
Ashoka Lella

Reputation: 6729

Use the getattr function

members = [getattr(self, attr) for attr in dir(self) if not attr.startswith("__")]

getattr(self, 'attr') is equivalent of self.attr

Upvotes: 4

Related Questions