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

2022-01-14 00:00:00 python namespaces

问题描述

谁能用足够的例子向我解释一下b/w有什么区别

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

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

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

>>> dir(1)  

除了它们显示出减少的属性数量和按顺序排列的方法.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.)

编辑

>>>obj.__class__.__name__  #gives the class name of object  
>>>dir(obj)                #gives attributes & methods  
>>>dir()                   #gives current scope/namespace
>>>obj.__dict__            #gives attributes


解决方案

dir() 允许您通过定义 __dir__() 自定义对象报告的属性.

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

从手册中,如果 __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.

这也是 inspect.getmembers() 返回的内容,只不过它返回的是 (name, attribute) 的元组,而不仅仅是名称.

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

object.__dict__{key: attribute, key2: atrribute2} 等形式的字典.

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

object.__dict__.keys() 有其他两个所缺少的.

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

来自 inspect.getmembers() 上的文档:

当参数是一个类时,getmembers() 不返回元类属性(此行为继承自 dir() 函数).

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

对于 int.__dict__.keys(),这是

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

总结一下,dir()inspect.getmembers()基本相同,而__dict__是包含元类属性的完整命名空间.

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

相关文章