原英文帮助文档:

dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

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__().

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • 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.

The resulting list is sorted alphabetically. For example:

>>> import struct
>>> dir() # show the names in the module namespace # doctest: +SKIP
['__builtins__', '__name__', 'struct']
>>> dir(struct) # show the names in the struct module # doctest: +SKIP
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
'__initializing__', '__loader__', '__name__', '__package__',
'_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
'unpack', 'unpack_from']
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']

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.

————————(我是分割线)————————

中文解释:

不带参数,返回当前本地作用域的名称列表。

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>>

使用参数,尝试返回该对象的有效属性列表。

>>> a = "string"
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
>>>

如果对象有一个名字叫__dir__()  的方法(函数),则将调用此方法,并且必须返回属性列表。

(大多数常见对象都有__dir__()方法  )

这允许实现自定义__getattr__() 或 __getattribute__()函数的对象自定义dir()报告其属性的方式。

如果对象不提供__dir__() ,则函数将尽力从对象的__dict__ 属性(如果其已经从类型对象手机信息去定义的话)

结果列表不一定完整,并且在对象具有自定义的__getattr__()时可能不准确。

默认的dir()机制,对不同类型的对象的行为不同,因为它试图生成最相关而不是最完整的信息。

如果对象是模块,则列表包含模块属性的名称。

如果对象是类型或类对象,则列表包含其属性的名称,并递归地包含其基的属性的名称。否则列表将包含对象的属性名、类的属性名,以及类的基类的递归属性名。

结果列表按字母顺序排序,如:

>>> import struct
>>> dir() # show the names in the module namespace # doctest: +SKIP
['__builtins__', '__name__', 'struct']
>>> dir(struct) # show the names in the struct module # doctest: +SKIP
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
'__initializing__', '__loader__', '__name__', '__package__',
'_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
'unpack', 'unpack_from']
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']

备注:

因为提供dir()主要是为了方便在交互提示下使用,因此它试图提供一组有趣的名称,而不是提供一组严格或一致定义的名称,并且其详细行为可能会在不同版本中发生变化。

例如当参数是类时,元类属性不在结果列表属性中。

———————(我是分割线)————————

————————(我是分割线)————————

参考:

1. Python 3.7.2 documentation

2. RUNOOB.COM:https://www.runoob.com/python/python-func-dir.html

备注:

初次编辑时间:2019年9月21日22:06:44

第一次修改时间:2019年9月21日22:10:14   / 添加环境信息

环境:Windows 7   / Python 3.7.2

最新文章

  1. iOS项目开发中的知识点与问题收集整理②(Part 二)
  2. java统计汉字
  3. Oracle常用命令
  4. php socket的一些问题
  5. Hadoop第13周练习—HBase作业
  6. 什么是网络爬虫(Spider) 程序
  7. LC.exe exited with code -1
  8. android中判断sim卡状态和读取联系人资料的方法
  9. 【QT】视频播放+文件选择
  10. python(3)-内置函数
  11. angular的post提交
  12. HDU 1247
  13. C# 如何查看源程序的IL代码
  14. join函数——Gevent源码分析
  15. 开源作业调度工具实现开源的Datax、Sqoop、Kettle等ETL工具的作业批量自动化调度
  16. 一步一个坑 - WinDbg调试.NET程序
  17. vue兄弟之间传值 bus中央事件总线
  18. 哈希表(Hash Map)
  19. mysql查看执行sql语句的记录日志
  20. AngularJS——第7章 依赖注入

热门文章

  1. 【Python之路】特别篇--生成器(constructor)、迭代器(iterator)、可迭代对象(iterable)
  2. Navicat导出表结构
  3. matplotlib中 plt.plot() 函数中**kwargs的参数形式
  4. 28.Python list列表详解
  5. HDU 5795 A Simple Nim ——(Nim博弈 + 打表)
  6. [题解] [JLOI2013] 卡牌游戏
  7. POJ2942Knights of the round table
  8. hive分区表插入一条测试数据
  9. 线程系列5--java中的ThreadLocal类实现线程范围内的数据共享(二)
  10. Leetcode题目20.有效的括号(简单)