views:

6992

answers:

7

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"]

Thanks guys!

Edit: I originally had asked for class variables erroneously. Thanks to all who brought this to my attention!

+12  A: 

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

Try this

>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()
cnu
FWIW, the inspect module gives you a more reliable method than relying on __dict__, which not all instances have.
Thomas Wouters
What kind of an instance does not have __dict__? I've never encountered one.
Carl Meyer
Certain built-in types, such as int. Try saying "x = 5" and then "x.__dict__" and you'll get an AttributeError
Eli Courtwright
Also, anything that uses __slots__.
Thomas Wouters
Why would you want to try and get the class instance variables of an int? It's not even a class (although I could be wrong on that).
Martin Sherburn
+9  A: 

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.

Thomas Wouters
Downvoting because "you can't get a list of instance attributes" is simply wrong: both vars() and __dict__ give you exactly that.
Carl Meyer
I assume he meant "you can't get a list of all possible instance attributes". For example, I often use lazy generation and the @property decorator to add an instance variable the first time it's requested. Using __dict__ would tell you about this variable once it existed but not beforehand.
Eli Courtwright
I didn't downvote, and please notice what I actually said: you can't get a list of instance attributes *given just a class*, which is what the code accompanying the question tries to do.
Thomas Wouters
@Carl: Please educate yourself before writing false comments and downvoting based your lack of knowledge.
nikow
+4  A: 

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

>>> hi_obj = hi()
>>> hasattr(hi_obj, "some attribute")
daniel
+1  A: 

Your example shows "instance variables", not really class variables.

Look in hi_obj.__class__.__dict__.items() for the class variables, along with other other class members like member functions and the containing module.

class Hi( object ):
    class_var = ( 23, 'skidoo' ) # class variable
    def __init__( self ):
        self.ii = "foo" # instance variable
        self.jj = "bar"

Class variables are shared by all instances of the class.

S.Lott
+10  A: 

Use vars()

class Foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2

vars(A()) #==> {'a': 1, 'b': 2}
vars(A()).keys() #==> ['a', 'b']
Jeremy Cantrell
+1 I personally think this syntax is cleaner than using __dict__, since attributes with double underscores are supposed to be "private" in Python syntax.
Martin W
@Martin: `__method` is private, `__method__` is a special method, not necessarily private; I would like to say the special methods define an object's capabilites rather than methods.
kaizer.se
+4  A: 

@Jeremy,

I don't have enough rep to comment... but,

>>> print vars.__doc__
vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.

In otherwords, it essentially just wraps __dict__

daniel
i agree, i actually meant to include that. i just think vars() looks better
Jeremy Cantrell
+2  A: 

Although not directly an answer to the OP question, there is a pretty sweet way of finding out what variables are in scope in a function. take a look at this code:

>>> def f(x, y):
    z = x**2 + y**2
    sqrt_z = z**.5
    return sqrt_z

>>> f.func_code.co_varnames
('x', 'y', 'z', 'sqrt_z')
>>>

The func_code attribute has all kinds of interesting things in it. It allows you todo some cool stuff. Here is an example of how I have have used this:

def exec_command(self, cmd, msg, sig):

    def message(msg):
        a = self.link.process(self.link.recieved_message(msg))
        self.exec_command(*a)

    def error(msg):
        self.printer.printInfo(msg)

    def set_usrlist(msg):
        self.client.connected_users = msg

    def chatmessage(msg):
        self.printer.printInfo(msg)

    if not locals().has_key(cmd): return
    cmd = locals()[cmd]

    try:
        if 'sig' in cmd.func_code.co_varnames and \
                       'msg' in cmd.func_code.co_varnames: 
            cmd(msg, sig)
        elif 'msg' in cmd.func_code.co_varnames: 
            cmd(msg)
        else:
            cmd()
    except Exception, e:
        print '\n-----------ERROR-----------'
        print 'error: ', e
        print 'Error proccessing: ', cmd.__name__
        print 'Message: ', msg
        print 'Sig: ', sig
        print '-----------ERROR-----------\n'
tim.tadh