Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Liệt kê tất cả hàm trong module Python

Dùng dir(module) để lấy tất cả attribute/method của module. Ví dụ:

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

Nhưng như bạn thấy, attribute của module (__name__, __doc__, v.v.) cũng được liệt kê. Bạn tạo hàm lọc dùng predicate isfunction và getmembers(module, predicate) để lấy member của module. Ví dụ:

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

Lưu ý: cách này không chạy cho built-in module vì type của hàm module đó không phải function mà là built-in function.