我想知道dir()内置函数的文档是否错误。特别是,哪些对象属性可能不是由dir()?返回的列表的一部分?
对于类对象和其他对象,文档说该列表包含“其属性”,这意味着属性的完整集合(而不是“某些”)?
Python v. 3.9 @ macOS 10.15.7
Help on built-in function dir in module builtins:
dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
Run Code Online (Sandbox Code Playgroud)
在 Python 中,属性不一定是对象上的事物,也不一定是类上的字段。例如,__getattr__可以按需定义任意属性。因此,没有通用的、健壮的方法来发现属性而不实际访问它。
如果对象未提供
__dir__(),则函数会尽力从对象的__dict__属性(如果已定义)及其类型对象中收集信息。结果列表不一定完整,当对象具有自定义__getattr__().
没有未涵盖的固定属性集dir-dir使用启发式和__dir__钩子,因此任何属性可能会或可能不会被发现。通常,对于行为良好的对象,可以期望公共属性对 可见dir。私有属性和特别是特殊属性是要从dir.
>>> '__dict__' in dir(object)
False
>>> hasattr(object, '__dict__')
True
Run Code Online (Sandbox Code Playgroud)
注意:因为
dir()主要是为了在交互式提示下使用方便,所以它尝试提供一组有趣的名称,而不是尝试提供一组严格或一致定义的名称,并且它的详细行为可能会随着版本的不同而改变。例如,当参数是类时,元类属性不在结果列表中。
(所有引用自文档 » Python 标准库 » 内置函数: dir)
| 归档时间: |
|
| 查看次数: |
219 次 |
| 最近记录: |