Python 内置函数 dir()

你的名字 2022-05-14 14:34 338阅读 0赞

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

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

使用 dir()

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

  1. >>> import math # 内置模块 math
  2. >>> dir(math)
  3. ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh',
  4. 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc',
  5. 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf',
  6. 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

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

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

  1. >>> math.__name__
  2. 'math'

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

  1. >>> s = 'Hello'
  2. >>> l = [1, 2, 3]
  3. >>> abs = math.fabs
  4. >>> dir()
  5. ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'l',
  6. 'math', 's']

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

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

自定义对象

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

  1. >>> class Person:
  2. ... def __dir__(self):
  3. ... return ['name', 'sex', 'age']
  4. ...
  5. >>> p = Person()
  6. >>> dir(p)
  7. ['age', 'name', 'sex']

参考:https://blog.csdn.net/liang19890820/article/details/75127738

发表评论

表情:
评论列表 (有 0 条评论,338人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python-函数

    从下图中可以知道python3中有如下这些内置函数 图一 下面我们一一了解下每个函数的用法: abs() abs() 函数是取绝对值的函数,在C语言只中有也有一个abs

    相关 Python 函数 dir()

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