Discover instance variables

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jul 16 14:06:45 EDT 2007


En Mon, 16 Jul 2007 14:25:48 -0300, JonathanB <doulos05 at gmail.com>  
escribió:

> Ok, I know there has to be a way to do this, but my google-fu fails me
> (once more). I have a class with instance variables (or should they be
> called attributes, I'm newish to programming and get really confused
> with OO sometimes), like the one in this example:
>
> class Foo():
>     self.a = "bar"
>     self.z = "test"
>     self.var = 2
>
> foo = Foo()
>
> I want to print a list of the variables (strings, integers, etc) in
> Foo, without knowing their names. So that the user who needs to change
> a peice of information can view the variable list, enter the name of
> the variable they need to change and then make the change. This is

You should define more precisely *which* attributes do you actually want  
in the list, but I think this may serve as a starting point:

py> def get_attributes(obj):
...   return [attr for attr in dir(obj) if not attr.startswith('_') and
...             type(getattr(obj,attr)) in (
...               int,str,unicode,float,dict,list,tuple)]
...
py> f=open("c:\\test.py")
py> get_attributes(f)
['mode', 'name', 'softspace']

The list keeps only the types explicitely enumerated. Other types are  
excluded, as well as names starting with "_". Another criterion would be  
`not attr.startswith('_') and not callable(getattr(obj,attr))`

-- 
Gabriel Genellina




More information about the Python-list mailing list