Discover instance variables

Dave Baum Dave.Baum at motorola.com
Tue Jul 17 12:32:33 EDT 2007


In article <1184606748.599294.293570 at n60g2000hse.googlegroups.com>,
 JonathanB <doulos05 at gmail.com> wrote:

> I can handle the formatting and changing the variable itself, no
> problem, but how do I get a list of all the variables in a class
> instance? I almost put a list in there called vars and appended all
> the variables to it so I could iterate the list, but this sounds like
> something useful enough that someone has come up with a better way to
> do it than that. It almost looks like self.__dir__() is what I want,
> but that returns methods as well, correct? I only want variables, but
> I can't think of how to do a list comprehension that would remove the
> methods.

For simple cases, the object's __dict__ will probably give you what you 
want.  By default, that's where an object's instance variables are 
stored, and you can just examine the keys, etc:

class Foo(object):
     def __init__(self):
         self.a = "bar"
         self.z = "test"
         self.var = 2
 
foo = Foo()
print foo.__dict__

-> {'a': 'bar', 'var': 2, 'z': 'test'}

However, there are lots of ways to bypass using the __dict__ to hold 
attributes.  If the class uses any of these techniques, __dict__ either 
will not exist or may not be complete.  A few of the techniques that 
come to mind are:

* custom __getattr__/__setattr__ methods (or __getattribute__ in a new 
style class)

* descriptors (http://docs.python.org/ref/descriptors.html)

* using __slots__ in a new style class


Dave



More information about the Python-list mailing list