首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >dir()内置函数返回“(某些)给定对象的属性”意味着什么?

dir()内置函数返回“(某些)给定对象的属性”意味着什么?
EN

Stack Overflow用户
提问于 2020-11-17 08:27:38
回答 1查看 584关注 0票数 5

我想知道文档对于dir()内置函数是否错误。特别是,哪些对象属性可能不是dir()返回的列表的一部分?

对于类对象和其他对象,文档都说列表包含“它的属性”,这意味着完整的属性集(而不是“某些属性”)?

Python诉3.9 @ macOS 10.15.7

代码语言:javascript
复制
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.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-17 08:47:00

在Python中,属性不一定是对象上的东西,也不一定是类中的字段。例如,可以按需定义任意属性。。因此,在不实际访问属性的情况下,没有发现属性的通用、健壮的方法。

如果对象不提供__dir__(),则函数会尽最大努力从对象的__dict__属性(如果定义的话)以及从其类型对象收集信息。结果列表不一定完整,当对象具有自定义__getattr__()时,可能不准确。

dir没有固定的属性集-- dir使用启发式方法,__dir__挂钩,因此任何属性都可能--或者可能--不会被发现。通常,对于行为良好的对象,可以期望dir可以看到公共属性。私有属性,特别是特殊属性,是被排除在dir之外的候选属性。

代码语言:javascript
复制
>>> '__dict__' in dir(object)
False
>>> hasattr(object, '__dict__')
True

注意:由于提供dir()主要是为了便于在交互式提示符下使用,所以它尝试提供一组有趣的名称,而不是试图提供严格或一致定义的名称集,而且它的详细行为可能在不同版本之间发生变化。例如,当参数是类时,元类属性不在结果列表中。

(所有来自Python标准库内置函数: dir的引号)

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64871685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档