Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

List ทุก Function ใน Python Module (dir + inspect)

ใช้ dir(module) ดู Attribute ทั้งหมด แล้ว Filter ด้วย inspect.isfunction

Basic: dir()

>>> import math
>>> dir(math)
['__doc__', '__name__', 'acos', 'acosh', 'asin', ..., 'sqrt', 'tan', 'tanh', 'trunc']

Filter เฉพาะ Function (User-defined)

>>> from inspect import getmembers, isfunction
>&>> import helloworld
>>> [name for name, obj in getmembers(helloworld) if isfunction(obj)]
['hello_world']

Built-in Modules (C Extension)

isfunction จะเป็น False (Type คือ builtin_function_or_method) ใช้ inspect.isbuiltin แทน

>>> [name for name, obj in getmembers(math) if inspect.isbuiltin(obj)]
['acos', 'acosh', ..., 'sqrt', 'tan', 'trunc']

รวมทั้ง Function และ Built-in

import inspect
callables = [name for name, obj in getmembers(math) if callable(obj)]