Python 内置函数 dir()

网友投稿 280 2022-08-23


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']


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spring Bean生命周期之Bean元信息的配置与解析阶段详解
下一篇:Python 文件 IO(python和java哪个更值得学)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~