looping over all member variables of a class in python

Python

Python Problem Overview


How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

    def as_list(self)
       ret = []
       for field in XXX:
           if getattr(self, field):
               ret.append(field)
       return ",".join(ret)

this should return

>>> e = Example()
>>> e.as_list()
bool143, bool2, foo

Python Solutions


Solution 1 - Python

dir(obj)

gives you all attributes of the object. You need to filter out the members from methods etc yourself:

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

example = Example()
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print members   

Will give you:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']

Solution 2 - Python

If you want only the variables (without functions) use:

vars(your_object)

Solution 3 - Python

@truppo: your answer is almost correct, but callable will always return false since you're just passing in a string. You need something like the following:

[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")]

which will filter out functions

Solution 4 - Python

>>> a = Example()
>>> dir(a)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__','__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__','__sizeof__', '__str__', '__subclasshook__', 'bool143', 'bool2', 'blah','foo', 'foobar2000', 'as_list']

—as you see, that gives you all attributes, so you'll have to filter out a little bit. But basically, dir() is what you're looking for.

Solution 5 - Python

Similar to vars(), one can use the below code to list all class attributes. It is equivalent to vars(example).keys().

example.__dict__.keys()

Solution 6 - Python

ClassName.__dict__["__doc__"]

This will filter out functions, in-built variables etc. and give you just the fields that you need!

Solution 7 - Python

row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns} if r else {}

Use this.

Solution 8 - Python

    class Employee:
    '''
    This class creates class employee with three attributes 
    and one function or method
    '''

    def __init__(self, first, last, salary):
        self.first = first
        self.last = last
        self.salary = salary

    def fullname(self):
        fullname=self.first + ' ' + self.last
        return fullname

emp1 = Employee('Abhijeet', 'Pandey', 20000)
emp2 = Employee('John', 'Smith', 50000)
    
print('To get attributes of an instance', set(dir(emp1))-set(dir(Employee))) # you can now loop over

Solution 9 - Python

The easy way to do this is to save all instances of the class in a list.

a = Example()
b = Example()
all_examples = [ a, b ]

Objects don't spring into existence spontaneously. Some part of your program created them for a reason. The creation is done for a reason. Collecting them in a list can also be done for a reason.

If you use a factory, you can do this.

class ExampleFactory( object ):
    def __init__( self ):
        self.all_examples= []
    def __call__( self, *args, **kw ):
        e = Example( *args, **kw )
        self.all_examples.append( e )
        return e
    def all( self ):
        return all_examples

makeExample= ExampleFactory()
a = makeExample()
b = makeExample()
for i in makeExample.all():
    print i

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpriestcView Question on Stackoverflow
Solution 1 - PythonmthurlinView Answer on Stackoverflow
Solution 2 - PythonNimoView Answer on Stackoverflow
Solution 3 - Pythonuser235925View Answer on Stackoverflow
Solution 4 - PythonbalphaView Answer on Stackoverflow
Solution 5 - PythonMehdiView Answer on Stackoverflow
Solution 6 - PythonHyuga HinataView Answer on Stackoverflow
Solution 7 - Pythonuser1825586View Answer on Stackoverflow
Solution 8 - PythonAbhijeet PandeyView Answer on Stackoverflow
Solution 9 - PythonS.LottView Answer on Stackoverflow