原英文帮助文档:

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. Neko does Maths CodeForces - 1152C 数论欧几里得

    Neko does MathsCodeForces - 1152C 题目大意:给两个正整数a,b,找到一个非负整数k使得,a+k和b+k的最小公倍数最小,如果有多个k使得最小公倍数最小的话,输出最小的 ...

  2. Jmeter(十)断言

    断言是我们在做自动化测试中常用的一个功能,用于检查测试中响应数据是否符合预期. 使用断言的目的:在request的返回层面增加一层判断机制:因为request成功了,并不代表结果一定正确. 下面我们就 ...

  3. Linux-expect脚本-编写一个expect脚本

    1.声明expect #!/usr/bin/expect -f 2.设置超时时间,获取参数 set ip [lindex $argv 0 ] //接收第一个参数,并设置IP set password ...

  4. Apache Ranger && HDFS

    Apache Ranger && HDFS 标签(空格分隔): Hadoop HDFS HDFS对于任何Hadoop大数据平台来说都是核心组成部分,为了加强对Hadoop平台的数据保护 ...

  5. What makes a good feature

    import numpy as np import matplotlib.pyplot as plt greyhounds = 500 # 灰猎犬500只 labs = 500 # 拉布拉多犬500只 ...

  6. IDEA如何将写好的java类(UDF函数)打成jar包上传linux

    一.编写一个UDF函数,实现将字符串大写转小写 import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.Text; ...

  7. Yum:[Errno 5] [Errno 2] No such file or directory

    出现这样的问题,就是因为之前python2升级到python3之后,yum有些配置文件定位不到之前的python2了,所以这里需要改掉两个配置文件就不会出事了. yum安装软件时,可以连接yum 仓库 ...

  8. java编程出现的错误对应的解决方法

    error: could not open D:\java\jre1.8\lib\amd64\jvm.cfg 解决方法:把java的环境变量%JAVA_HOME%/bin上移到最上面 优化 查看网页源 ...

  9. 如何在Linux上安装Composer

    我们可以通过 Composer 镜像安装 composer ,在这之前,请确认您的机器上已经安装了PHP,并可以通过php来执行命令.如果您的服务器上必须通过全路径来执行(/usr/local/php ...

  10. Excel中,如何将人名按姓和名分开?

    在Excel中,怎么将姓名分开呢? 用到三个函数: left函数:从文本字符串的左端开始,返回指定个数的字符: right函数:从字符串右端开始,返回指定个数的字符: len函数:返回文本串的字符数 ...