我的系统上安装了一个Python模块,我希望能够看到其中有哪些函数/类/方法可用。
我想对每一个都调用帮助函数。在Ruby中,我可以做一些类似ClassName的事情。方法获取该类上所有可用方法的列表。Python中有类似的东西吗?
例如:
from somemodule import foo
print(foo.methods) # or whatever is the correct method to call
我的系统上安装了一个Python模块,我希望能够看到其中有哪些函数/类/方法可用。
我想对每一个都调用帮助函数。在Ruby中,我可以做一些类似ClassName的事情。方法获取该类上所有可用方法的列表。Python中有类似的东西吗?
例如:
from somemodule import foo
print(foo.methods) # or whatever is the correct method to call
当前回答
使用vars(module),然后使用inspect.isfunction过滤掉任何不是函数的东西:
import inspect
import my_module
my_module_functions = [f for _, f in vars(my_module).values() if inspect.isfunction(f)]
vars相对于dir或inspect的优势。Getmembers是按函数定义的顺序返回函数,而不是按字母顺序排序。
此外,这将包括my_module导入的函数,如果你想过滤掉它们,只获得my_module中定义的函数,请参阅我的问题获取Python模块中所有已定义的函数。
其他回答
import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]
Dir(模块)是使用脚本或标准解释器时的标准方式,正如大多数回答中提到的那样。
然而,对于交互式python shell(如IPython),您可以使用制表符完成来获得模块中定义的所有对象的概述。 这比使用脚本和打印查看模块中定义的内容要方便得多。
模块。<tab>将显示模块中定义的所有对象(函数,类等) module.ClassX。<tab>将显示一个类的方法和属性 module.function_xy吗?还是module.ClassX.method_xy ?是否会显示该函数/方法的文档字符串 module.function_x ? ?还是module.SomeClass.method_xy ? ?将显示函数/方法的源代码。
一旦你导入了模块,你可以这样做:
help(modulename)
... 以交互方式一次性获得所有函数的文档。或者你可以用:
dir(modulename)
... 简单地列出模块中定义的所有函数和变量的名称。
对于全局函数,dir()是要使用的命令(正如大多数回答中提到的那样),但是它同时列出了公共函数和非公共函数。
例如:
>>> import re
>>> dir(re)
返回如下函数/类:
'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'
其中一些通常不用于一般编程使用(而是由模块本身使用,除非DunderAliases如__doc__, __file__等)。由于这个原因,将它们与公共对象一起列出可能没有用处(这就是Python如何知道从模块import *中使用时获取什么)。
__all__可以用来解决这个问题,它返回一个模块中所有公共函数和类的列表(那些不以下划线- _开头的)。看到 有人能用Python解释__all__吗?对于__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__'
>>>
import types
import yourmodule
print([getattr(yourmodule, a) for a in dir(yourmodule)
if isinstance(getattr(yourmodule, a), types.FunctionType)])