3

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.

Dap
  • 2,309
  • 5
  • 32
  • 44

2 Answers2

4

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

Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39
2

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']
greole
  • 4,523
  • 5
  • 29
  • 49