inspect.getmembers() vs __dict__.items() vs dir()(inspect.getmembers() vs __dict__.items() vs dir())
问题描述
谁能用足够的例子向我解释一下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.
这篇关于inspect.getmembers() vs __dict__.items() vs dir()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:inspect.getmembers() vs __dict__.items() vs dir()
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01