inspect.getmembers() vs __dict__.items() vs dir()

前端 未结 1 914
情书的邮戳
情书的邮戳 2020-12-03 04:32

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

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

an

相关标签:
1条回答
  • 2020-12-03 05:08

    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.

    0 讨论(0)
提交回复
热议问题