tags:

views:

211

answers:

4

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
+2  A: 
balpha
+8  A: 
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


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

Will give you:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']
truppo
A: 

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
S.Lott
I like the idea (I might actually use that in a current project). It's not an answer to the question, though: The OP wants to list the attributes, not the instances themselves.
balpha
@balpha: Ooops. Didn't read the question. 90% of the time, it's a duplicate of "how do I find all instances of a class." The actual question (now that you point it out) isn't sensible. You know the instance variables, just make a list.
S.Lott
A: 

@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("__")]