listing attributes

James Stroud jstroud at ucla.edu
Mon Feb 13 22:17:00 EST 2006


Thomas Girod wrote:
> Hi there.
> 
> I'm trying to get a list of attributes from a class. The dir() function
> seems to be convenient, but unfortunately it lists to much - i don't
> need the methods, neither the built-in variables.
> 
> In fact, all my variables are referencing to objects of the same type.
> Can anyone suggest me a way to get this list of variables ?
> 
> Thanks
> 
> Thomas
> 


Here's a "smart-ass" example:

py> import random
py> class C:
...   def __repr__(self):
...     return "<Im_a_C!>"
...
py> alist = [1,2,3,4,5] + [C() for x in xrange(5)]
py> alist
[1, 2, 3, 4, 5, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>]
py> class Obj:
...   def __repr__(self):
...     return str([getattr(self, o) for o in dir(self) \
...       if isinstance(getattr(self, o), C)])
...
py> anobj = Obj()
py> newlist = [choice(alist) for x in xrange(10)]
py> newlist
[<Im_a_C!>, <Im_a_C!>, 5, 1, 5, 4, 4, <Im_a_C!>, <Im_a_C!>, 3]
py> [setattr(anobj, *tup) for tup in zip('abcdefghij', newlist)]
[None, None, None, None, None, None, None, None, None, None]
py> anobj.a
<Im_a_C!>
py> anobj.b
<Im_a_C!>
py> anobj.c
5
py> anobj.d
1
py> print anobj
[<Im_a_C!>, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>]

James



More information about the Python-list mailing list