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
Methods to verify the type of token:isclass(): The isclass() method returns True if that object is a class or false otherwise. When it is combined with the getmembers() functions it shows the class and its type. It is used to inspect live classes.
inspect. stack() returns a list with frame records. In function whoami() : inspect. stack()[1] is the frame record of the function that calls whoami , like foo() and bar() . The fourth element of the frame record ( inspect.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With