gpt4 book ai didi

python - dir() 内置函数返回 "(some of) the attributes of the given object"是什么意思?

转载 作者:行者123 更新时间:2023-12-03 16:19:59 25 4
gpt4 key购买 nike

我想知道 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.

最佳答案

在 Python 中,属性不一定是对象上的事物或类上的字段。例如, __getattr__ can define arbitrary attributes on-demand .因此,没有一种通用的、稳健的方法可以在不实际访问属性的情况下发现属性。

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

dir 没有涵盖的固定属性集。 – dir使用启发式和 __dir__钩子(Hook),所以任何属性都可能会或可能不会被发现。一般而言,对于行为良好的对象,可以预期 dir 可以看到公共(public)属性。 .私有(private)属性和特别特殊的属性是被排除在 dir 之外的候选对象。 .
>>> '__dict__' in dir(object)
False
>>> hasattr(object, '__dict__')
True

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.


(所有引述来自 Documentation » The Python Standard Library » Built-in Functions: dir )

关于python - dir() 内置函数返回 "(some of) the attributes of the given object"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64871685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com