Inspecting the Instance Vars in a class/object - How?

Diez B. Roggisch deets at nospam.web.de
Wed Aug 27 05:06:27 EDT 2008


BrendanC wrote:

> I'm trying to understand reflection/introspection in Python. How can I
> identify the the type of attribute (e.g. instance var) in a class?
> The following returns all the class attributes (methods and instance
> vars).
> 
> However I'm interested in identifying the type of value for each case
> - (e.g. I'd like to identify the instance variables separately). (The
> Inspect module has an ismethod method, but not an isinstancevariable
> method).

Because there is no such thing, as it is not a *type*. It's a question on
where the value is stored.

Every *instance* has a dictionary holding it's data. You can normally access
it using __dict__. 

But it's not "pure" in the sense that only the variables you created
yourself are contained. It also contains the reference to the class.

On the class, there is also a __dict__, which contains the
method-descriptors and class-variables.

In the face of multi-inheritance, things get even more complicated, as then
the values are acquired through MRO-lookup.
 
> e.g. In the following example I'd like to extract the class vars
> strvar and intNum and ignore the methods/other attribute types.
> 
> What is the best way  to do this?
> 
> class test:
> # Dummy Class for reflection testing
>     strVar = '1234'
>     intNum = 0
> 
>     def nullmethod():
>         pass
> 
>     def addmethod(self,v1, v2):
>         v = v1 + v2
>         return v
> 
> if __name__ == "__main__":
>   mytest = test()
>   for key in dir(mytest):
>         value = getattr(object, key)
>         print 'Key: %s ; Value %s '  % (str(key) ,str(value))

if name in mytest.__dict__:
    print "instance variable"




More information about the Python-list mailing list