Discover instance variables

Bjoern Schliessmann usenet-mail-0306.20.chr0n0ss at spamgourmet.com
Mon Jul 16 14:05:34 EDT 2007


JonathanB wrote:
> 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),

To complete confusion, those terms vary with languages :)

> like the one in this example:
> 
> class Foo():
>     self.a = "bar"
>     self.z = "test"
>     self.var = 2

This will not work. Please use working code for examples.

> 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. 

I'd use exactly this, since there may be attributes you don't want
to be changed from outside (perhaps __class__).

> 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. 

That's quite a problem with your concept. There are no variables and
methods. There are only attributes. Attributes may be objects. Some
objects may be callable (like function objects).

If you know exactly what you want to be accessible like this, you
could filter __dir__() output with name/callable/isinstance tests.

Regards,


Björn


-- 
BOFH excuse #320:

You've been infected by the Telescoping Hubble virus.




More information about the Python-list mailing list