Jan Kaliszewski zuo at
Sun Jan 24 17:17:07 CET 2010

24-01-2010, 16:56:42 Jan Kaliszewski <zuo at> wrote:

> 24-01-2010, 16:28:26 Robert P. J. Day <rpjday at> wrote
>>   once again, probably a trivial question but i googled and didn't
>> get an obvious solution.  how to list the attributes of a *class*?
>      dir(type(an_obj))
> or more reliable:
>      list(vars(type(an_obj)))
> (dir() uses __dir__ which can be implemented in any way, and default  
> implementation, accordinto to the docs, "attempts to produce the most  
> relevant, rather than complete, information").

I missed one important thing:

* dir(a_type) mostly applies to attributes of a_type *and* of its base  
types/classes [1].
* vars() applies only to attributes of this particular type (AFAIN  
vars(sth) and sth.__dict__ are practically the same).


     >>> class D(dict): pass
     >>> dir(D)
     ['__class__', '__contains__', '__delattr__', '__delitem__',  
'__dict__', '__doc__', '__eq__', '__format__', '__ge__',  
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__',  
'__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__',  
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',  
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',  
'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem',  
'setdefault', 'update', 'values']
     >>> list(vars(D))
     ['__dict__', '__module__', '__weakref__', '__doc__']


[1] In Python 3.x *type* and *class* is practically the same. (though  
built-in ones are denoted as *types* rather than *classes* -- using this  
naming convention a *class* is simply a user-defined *type*).

Jan Kaliszewski (zuo) <zuo at>

More information about the Python-list mailing list