如何列出Python模块中的所有功能?

您可以使用dir(module)获取模块的所有属性/方法。例如,

>>> import math
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

但是在这里您可以看到模块的属性(__name __,__ doc__等)也已列出。您可以创建一个简单的函数,使用isfunction谓词和getmembers(module,predicate)过滤掉这些函数,以获取模块的成员。例如,

>>> from inspect import getmembers, isfunction
>>> import helloworld
>>> print [o for o in getmembers(helloworld) if isfunction(o[1])]
['hello_world']

请注意,这不适用于内置模块,因为这些模块的功能类型不是功能而是内置功能。