我想知道文档对于dir()内置函数是否错误。特别是,哪些对象属性可能不是dir()返回的列表的一部分?
对于类对象和其他对象,文档都说列表包含“它的属性”,这意味着完整的属性集(而不是“某些属性”)?
Python诉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.发布于 2020-11-17 08:47:00
在Python中,属性不一定是对象上的东西,也不一定是类中的字段。例如,可以按需定义任意属性。。因此,在不实际访问属性的情况下,没有发现属性的通用、健壮的方法。
如果对象不提供
__dir__(),则函数会尽最大努力从对象的__dict__属性(如果定义的话)以及从其类型对象收集信息。结果列表不一定完整,当对象具有自定义__getattr__()时,可能不准确。
dir没有固定的属性集-- dir使用启发式方法,__dir__挂钩,因此任何属性都可能--或者可能--不会被发现。通常,对于行为良好的对象,可以期望dir可以看到公共属性。私有属性,特别是特殊属性,是被排除在dir之外的候选属性。
>>> '__dict__' in dir(object)
False
>>> hasattr(object, '__dict__')
True注意:由于提供
dir()主要是为了便于在交互式提示符下使用,所以它尝试提供一组有趣的名称,而不是试图提供严格或一致定义的名称集,而且它的详细行为可能在不同版本之间发生变化。例如,当参数是类时,元类属性不在结果列表中。
(所有来自Python标准库内置函数: dir的引号)
https://stackoverflow.com/questions/64871685
复制相似问题