Skip to content Skip to sidebar Skip to footer

How To Get Instance Variables In Python?

Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: class hi: def __init__(self): self.ii = 'foo' s

Solution 1:

Every object has a __dict__ variable containing all the variables and its values in it.

Try this

>>>hi_obj = hi()>>>hi_obj.__dict__.keys()

Solution 2:

Use vars()

classFoo(object):
    def__init__(self):
        self.a = 1
        self.b = 2vars(Foo()) #==> {'a': 1, 'b': 2}vars(Foo()).keys() #==> ['a', 'b']

Solution 3:

You normally can't get instance attributes given just a class, at least not without instantiating the class. You can get instance attributes given an instance, though, or class attributes given a class. See the 'inspect' module. You can't get a list of instance attributes because instances really can have anything as attribute, and -- as in your example -- the normal way to create them is to just assign to them in the __init__ method.

An exception is if your class uses slots, which is a fixed list of attributes that the class allows instances to have. Slots are explained in http://www.python.org/2.2.3/descrintro.html, but there are various pitfalls with slots; they affect memory layout, so multiple inheritance may be problematic, and inheritance in general has to take slots into account, too.

Solution 4:

You can also test if an object has a specific variable with:

>>>hi_obj = hi()>>>hasattr(hi_obj, "some attribute")

Solution 5:

Both the Vars() and dict methods will work for the example the OP posted, but they won't work for "loosely" defined objects like:

classfoo:
  a = 'foo'
  b = 'bar'

To print all non-callable attributes, you can use the following function:

defprintVars(object):
    for i in [v for v indir(object) ifnotcallable(getattr(object,v))]:
        print'\n%s:' % i
        exec('print object.%s\n\n') % i

Post a Comment for "How To Get Instance Variables In Python?"