原英文帮助文档:

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

【Python】【基础知识】【内置函数】【dir的使用方法】的更多相关文章

  1. 十六. Python基础(16)--内置函数-2

    十六. Python基础(16)--内置函数-2 1 ● 内置函数format() Convert a value to a "formatted" representation. ...

  2. 十五. Python基础(15)--内置函数-1

    十五. Python基础(15)--内置函数-1 1 ● eval(), exec(), compile() 执行字符串数据类型的python代码 检测#import os 'import' in c ...

  3. python基础(15):内置函数(一)

    1. 内置函数 什么是内置函数? 就是python给你提供的,拿来直接⽤的函数,比如print,input等等,截⽌到python版本3.6.2 python⼀共提供了68个内置函数.他们就是pyth ...

  4. python基础(内置函数+文件操作+lambda)

    一.内置函数 注:查看详细猛击这里 常用内置函数代码说明: # abs绝对值 # i = abs(-123) # print(i) #返回123,绝对值 # #all,循环参数,如果每个元素为真,那么 ...

  5. Python基础:内置函数

    本文基于Python 3.6.5的标准库文档编写,罗列了英文文档中介绍的所有内建函数,并对其用法进行了简要介绍. 下图来自Python官网:展示了所有的内置函数,共计68个(14*4+12),大家可以 ...

  6. 第六篇:python基础_6 内置函数与常用模块(一)

    本篇内容 内置函数 匿名函数 re模块 time模块 random模块 os模块 sys模块 json与pickle模块 shelve模块 一. 内置函数 1.定义 内置函数又被称为工厂函数. 2.常 ...

  7. Python基础编程 内置函数

    内置函数 内置函数(一定记住并且精通) print()屏幕输出 int():pass str():pass bool():pass set(): pass list() 将一个可迭代对象转换成列表 t ...

  8. Python基础_内置函数

        Built-in Functions     abs() delattr() hash() memoryview() set() all() dict() help() min() setat ...

  9. 学习PYTHON之路, DAY 4 - PYTHON 基础 4 (内置函数)

    注:查看详细请看https://docs.python.org/3/library/functions.html#next 一 all(), any() False: 0, Noe, '', [], ...

  10. Python基础、 内置函数

    一.概述 Python中内置了很多函数: 可以通过help().dir()方式查看函数的功能,使用内置函数通常效率更高 abs() abs函数接收一个数字对象,返回它的绝对值,如果接受的对象不是数字抛 ...

随机推荐

  1. ssh2整合: No bean named 'sessionFactory' is defined(求大神指点)

    applicationContext.xml 中已经配置 <bean id="sessionFactory" class="org.springframework. ...

  2. pdf缩略图上传组件

    之前仿造uploadify写了一个HTML5版的文件上传插件,没看过的朋友可以点此先看一下~得到了不少朋友的好评,我自己也用在了项目中,不论是用户头像上传,还是各种媒体文件的上传,以及各种个性的业务需 ...

  3. IIS+上传4G文件

    最近在学习百度的开源上传组件WebUploader,写了一些示例以记录.WebUploader的缺点是没有一个比较好的现成的界面,这个界面需要自己去实现.自由度高了一些. WebUploader是由B ...

  4. codevs 1094 FBI树 2004年NOIP全国联赛普及组 x

                         题目描述 Description 我们可以把由“0”和“1”组成的字符串分为三类:全“0”串称为B串,全“1”串称为I串,既含“0”又含“1”的串则称为F串. ...

  5. 背景(background)

    背景(background) 背景家族由5个主要的背景属性组成 background-color背景颜色 background-color:colorNome(取值 如:颜色名 red green. ...

  6. Vue.Draggable拖拽效果

    1.下载包:npm install vuedraggable 配置:package.json "dependencies": { "vuedraggable": ...

  7. Linux常用文本处理命令

    1.grep命令 echo 'zero\nzo\nzoo' | grep 'z.*o':将匹配以'z'开头以'o'结尾的所有字符串 echo 'zero\nzo\nzoo' | grep 'z.o': ...

  8. 修复Long类型太长转为JSON格式的时候出错的问题

    这边项目要求ID是自动生成的20位Long型数字 但是实际中应用的时候回发生一种问题就是,查询的时候debug的时候数据都正常,但是返回前端的时候就会发现,数据错误了. 大体就是类似于下面的这种情况. ...

  9. ftp协议在linux上的配置

    第一步:安装 yum install -y vsftpd 第二步:启动ftp服务:vsftpd [root@localhost ~]# systemctl start vsftpd 第三步:查看启动状 ...

  10. 学习UEFI 之你把C语言学好了码?学习UEFI 之你把C语言学好了吗?

    很多人在问我说: 怎样子把UEFI 学好?! 其实写BIOS 的人答案应该只有一个,把SPCE看懂看完然后融会贯通!这样子的答案好像跟没有是一样的! 小弟就以我的学习经验来分享给大家吧!(虽然我也没学 ...