对于全局函数 dir() 是要使用的命令(如大多数答案中所述),但是这将公共函数和非公共函数一起列出。
例如运行:
>>> import re
>>> dir(re)
返回函数/类,如:
'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'
其中一些通常不用于一般编程用途(但由模块本身使用,除了 DunderAliases,如 __doc__、__file__ 等)。出于这个原因,将它们与公共的一起列出可能没有用(这就是 Python 知道在使用 from module import * 时会得到什么的方式)。
__all__ 可以用来解决这个问题,它返回一个模块中所有公共函数和类的列表(那些不以下划线开头的 - _)。看
Can someone explain __all__ in Python?供__all__使用。
这是一个例子:
>>> import re
>>> re.__all__
['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'findall', 'finditer', 'compile', 'purge', 'template', 'escape', 'error', 'A', 'I', 'L', 'M', 'S', 'X', 'U', 'ASCII', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'UNICODE']
>>>
所有带下划线的函数和类都被删除了,只留下那些被定义为公共的,因此可以通过import *使用。
请注意,__all__ 并不总是被定义。如果不包含它,则会引发 AttributeError。
ast 模块就是一个例子:
>>> import ast
>>> ast.__all__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'ast' has no attribute '__all__'
>>>