参考链接: Python dir()

简述

在 Python 中,有大量的内置模块,模块中的定义(例如:变量、函数、类)众多,不可能全部都记住,这时 dir() 函数就非常有用了。

dir() 是一个内置函数,用于列出对象的所有属性及方法。在 Python 中,一切皆对象,模块也不例外,所以模块也可以使用 dir()。除了常用定义外,其它的不需要全部记住它,交给 dir() 就好了。

| 版权声明:一去、二三里,未经博主允许不得转载。

dir()

如果对 dir() 的用法不是很清楚,可以使用 help() 来查看帮助:

>>> help(dir)

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.

(END)

基本场景:

如果 dir() 没有参数,则返回当前作用域中的名称列表;否则,返回给定 object 的一个已排序的属性名称列表。如果对象提供了 __dir__() 方法,则它将会被使用;否则,使用默认的 dir() 逻辑,并返回。

使用 dir()

使用 dir() 可以查看指定模块中定义的名称,它返回的是一个已排序的字符串列表:

>>> import math  # 内置模块 math

>>> dir(math)

['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

其中,以下划线(_)开头的名称并不是自己定义的,而是与模块相关的默认属性。

例如,属性 __name__ 表示模块名称:

>>> math.__name__

'math'

如果没有参数,dir() 会列出当前作用域中的名称:

>>> s = 'Hello'

>>> l = [1, 2, 3]

>>> abs = math.fabs

>>> dir()

['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'l', 'math', 's']

通过导入 builtins 模块,可以获得内置函数、异常和其他对象的列表:

>>> import builtins

>>> dir(builtins)

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

自定义对象

根据 help 中的描述,可以看到:

If the object supplies a method named __dir__, it will be used;

也就是说,如果对象有 __dir__() 方法,则将会被使用:

>>> class Person:

...     def __dir__(self):

...         return ['name', 'sex', 'age']

...

>>> p = Person()

>>> dir(p)

['age', 'name', 'sex']

[转载] Python 内置函数 dir()相关推荐

  1. python内置函数 — dir()

    1.官方定义 格式:dir([object]) 没有实参,返回当前本地作用域中的名称列表. 有实参,返回参数对象的有效属性列表. 由于python中一切皆对象,所有object对象可以是模块,类型,类 ...

  2. [转载] Python内置函数-min函数和max函数-详解

    参考链接: Python min() 博文主要内容如下: max和min函数的使用介绍: 对可迭代对象元素进行比较,找到最大/最小值      max(iterable, *[, default=ob ...

  3. [转载] Python 内置函数 lambda、filter、map、reduce

    参考链接: Python lambda (匿名函数) | filter, map, reduce Python 内置了一些比较特殊且实用的函数,使用这些能使你的代码简洁而易读. 下面对 Python ...

  4. 【python】python内置函数——dir()获取对象的属性和方法

    dir()函数 不带参数时,返回当前范围内的变量.方法和定义的类型列表: 带参数时,返回参数的属性.方法列表: 如果参数包含方法__dir__(),该方法将会被调用: 如果参数不包含__dir__() ...

  5. 学习笔记———Python内置函数dir()

    dir([object])----可以带参数,也可以不带参数 1.当不带参数时,返回当前作用域内的变量.方法和定义的类型列表. >>>dir() ['__annotations__' ...

  6. [转载] python内置函数 compile()

    参考链接: Python compile() 描述 compile() 函数将一个字符串编译为字节代码. 语法 以下是 compile() 方法的语法: compile(source, filenam ...

  7. python中dir用法_Python内置函数dir详解

    1.命令介绍 最近学习并使用了一个python的内置函数dir,首先help一下: >>> help(dir) Help on built-in function dir in mo ...

  8. 学习Python的利器:内置函数dir()和help()

    (1)内置函数dir()用来查看对象的成员.在Python中所有的一切都是对象,除了整数.实数.复数.字符串.列表.元组.字典.集合等等,还有range对象.enumerate对象.zip对象.fil ...

  9. python学习高级篇(part6)--内置函数dir

    学习笔记,仅供参考,有错必纠 内置函数dir 对于类对象或实例对象,可以调用内置函数dir()获得其所有可以访问的属性和方法(包括从父类中继承的属性和方法)的列表. 类对象与实例对象的结果是有区别的, ...

最新文章

  1. 免费丨AI内行盛会!2021北京智源大会带你与图灵奖和200+位大牛一起共话AI
  2. ASP.NET中常用功能代码总结(3)——上传图片到数据库
  3. @async 没有异步_玩转javascript异步编程
  4. 今晚直播丨国产数据库入门:openGauss数据库的基本管理和SQL语句入门
  5. 微信小程序chooseImage(从本地相册选择图片或使用相机拍照)
  6. 块级元素行内元素内联元素
  7. 农行总行携手趣链科技上线区块链涉农电商融资产品
  8. 【TensorFlow系列】【九】利用tf.py_func自定义算子
  9. 解决安卓中页脚被输入法顶起的问题
  10. 防抖、节流及应用/风尚云网/前端/JavaScript学习
  11. 如何快速入门学习UG编程
  12. Python利用requests库爬取百度文库文章
  13. 服务器解析错误_常见的域名解析错误原因及应对方法
  14. 计算机英语常见计算符号,常见计算机英语词汇解释
  15. 苹果可穿戴设备项目背后的那些专家
  16. 关于Fusion on Apple Silicon的谨慎猜测
  17. 埃安崛起,新能源汽车下半场
  18. 扎心了,5年多工作经验,期望工资15k,HR只给了13k
  19. 四舍五入VS银行家舍入
  20. 迅雷API批量下载巨潮年报

热门文章

  1. jQuery的empty、remove、detach区别
  2. 2021下半年ICPC各类赛事时间日程
  3. UVa1587 - Box
  4. 路由器Lan、Wan短接问题
  5. JavaScript的for of语法遍历数组元素
  6. android环信退出登录,环信退出登陆的的问题
  7. window.onload和jQuery的ready函数区别
  8. Easy Summation 假的自然数幂的和
  9. JQueryDOM之属性操作
  10. map迭代器遍历_一口气写了 HashMap 的 7种遍历方式,被同事夸了