Alex Rivera | Logout

How to get instance variables in Python?

Asked 2008-09-20T19:30:24.580
156

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"
    self.kk = "bar"

Is there a way for me to do this:

>>> mystery_method(hi)
["ii", "kk"]

Edit: I originally had asked for class variables erroneously.

Edit
Report

1 Answer

196

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

Try this

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

Output

dict_keys(['ii', 'kk'])
answered 2008-09-20T19:34:17.050

Your Answer