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

标签 python namespaces

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

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

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

>>> dir(1)  

除了它们显示的属性和方法的数量按此顺序递减。 1 是整数(但它可以是任何类型。)


编辑

>>>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__() 没有定义:

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) 的元组,而不仅仅是名称。

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

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

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

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__是包含元类属性的完整命名空间.

关于python - inspect.getmembers() vs __dict__.items() vs dir(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6761106/

相关文章:

python - 如何在 Python 和 QML 中将 QJSValue 转换为 Python 列表?

python - 使用正则表达式 'or' 并同时捕获组

python - matplotlib 中带有标题、轴标签的确切图形大小

c++ - 在 C++ 中重命名一个类

c++ - 为什么对 isnan 的调用没有歧义? a.k.a. 使用引入 2 次相似函数声明的关键字

python - 制作一个 Python 脚本来加载目录中的所有 npy/npz 文件

clojure - :use fails in lein project

python - Tensorflow - S3 对象不存在

javascript - 当命名空间已存在时,Type.registerNamespace 会抛出错误

python - 将 Excel 中的多列合并为 pandas 中的一列