How to get instance variables in Python? How to get instance variables in Python? python python

How to get instance variables in Python?


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

Try this

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


Use vars()

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


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.