Discover instance variables

JonathanB doulos05 at gmail.com
Mon Jul 16 13:25:48 EDT 2007


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
what I'd like a sample run to look like:

Attributes for foo:
a = bar
z = test
var = 2

Change: a
New value: foobar
Change made!

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.

JonathanB




More information about the Python-list mailing list