33

Can anybody explain to me with adequate examples whats the difference b/w

>>> import inspect
>>> inspect.getmembers(1)

and

>>> type(1).__dict__.items()

and

>>> dir(1)  

except that they show an decreasing no.s of attributes & methods in that order. 1 is integer (but it can be of any type.)


EDIT

>>>obj.__class__.__name__  #gives the class name of object  
>>>dir(obj)                #gives attributes & methods  
>>>dir()                   #gives current scope/namespace
>>>obj.__dict__            #gives attributes
Jibin
  • 3,054
  • 7
  • 36
  • 51
  • 1
    Depending on your purpose, you may want to edit the last block again, replacing `object` for sth else (say, obj) and change the last comment from "gives attributes" to sth like "gives the _instance_ attributes" -- as when `dir(obj)` basically "includes inheritance", `obj.__dict__.keys()` does not – ジョージ Apr 25 '12 at 11:14

1 Answers1

24

dir() allows you to customize what attributes your object reports, by defining __dir__().

From the manual, if __dir__() is not defined:

If the object is a module object, the list contains the names of the module’s attributes.

If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

This is also what inspect.getmembers() returns, except it returns tuples of (name, attribute) instead of just the names.

object.__dict__ is a dictionary of the form {key: attribute, key2: atrribute2} etc.

object.__dict__.keys() has what the other two are lacking.

From the docs on inspect.getmembers():

getmembers() does not return metaclass attributes when the argument is a class (this behavior is inherited from the dir() function).

For int.__dict__.keys(), this is

['__setattr__', '__reduce_ex__', '__reduce__', '__class__', '__delattr__', '__subclasshook__', '__sizeof__', '__init__']

To summarize, dir() and inspect.getmembers() are basically the same, while __dict__ is the complete namespace including metaclass attributes.

Community
  • 1
  • 1
agf
  • 171,228
  • 44
  • 289
  • 238