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

BrendanC brencam at gmail.com
Wed Aug 27 03:12:23 EDT 2008


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

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







More information about the Python-list mailing list