How can access the list of all the build in functions for an module in python
如果我有一个称为"math"的模块,它可以称为导入"math",那么如何获取与"math"关联的所有内置函数的列表?
有一个dir函数,它列出了对象的所有(很好,几乎很多)属性。但是只过滤函数不是问题:
1 2 3 4 5 6 | >>>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'] >>> >>>[f for f in dir(math) if hasattr(getattr(math, f), '__call__')] # filter on functions ['acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] |
您可能会发现python自省指南是一个有用的资源,以及这个问题:如何检测python变量是否是函数?.
这就是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | >>> import math >>> help(math) Help on built-in module math: NAME math <snip> FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. acosh(...) acosh(x) Return the hyperbolic arc cosine (measured in radians) of x. asin(...) <snip> |
仅限内置函数:
1 2 3 | from inspect import getmembers, isfunction functions_list = [o for o in getmembers(my_module, isfunction)] |