Python 内置函数 dir()
来源:互联网 发布:追风软件 编辑:程序博客网 时间:2024/05/22 13:18
简述
在 Python 中,有大量的内置模块,模块中的定义(例如:变量、函数、类)众多,不可能全部都记住,这时 dir()
函数就非常有用了。
dir()
是一个内置函数,用于列出对象的所有属于及方法。在 Python 中,一切皆对象,模块也不例外,所以模块也可以使用 dir()
。除了常用定义外,其它的不需要全部记住它,交给 dir()
就好了。
- 简述
- dir
- 使用 dir
- 自定义对象
版权所有:一去丶二三里,转载请注明出处:http://blog.csdn.net/liang19890820
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']
阅读全文
0 0
- Python 内置函数 dir()
- Python标准库:内置函数dir([object])
- python常用内置函数dir,type,str等
- python dir函数
- python dir()函数作用
- python函数 - dir()
- 4.5 Python dir()函数
- python-dir()函数
- python dir()函数
- Python的dir函数
- python: dir函数
- Python的dir()函数
- 今天开始学Python(type,str,dir及其他内置函数)
- python内建函数 dir()
- python dir()内建函数
- Python函数---dir(),help(),type()
- python函数: 内置函数
- Python基础学习篇—dir()函数
- Leetcode 556. Next Greater Element III
- 动归-----编辑距离
- 朴素贝叶斯算法原理小结
- 前、中、后缀表达式和前、中、后序遍历
- java模式—装饰者模式
- Python 内置函数 dir()
- 判断单向链表是否回文
- 神经性风格化过程的特征控制
- 344. Reverse String
- 错误代码: 1381 You are not using binary logging 以及解决方式
- SQL注入攻击
- Cannot read property 'nodeName' of undefined
- poj3714 Raid (分治)
- Swing自动扫描服务程序总结