我的系统上安装了一个Python模块,我希望能够看到其中有哪些函数/类/方法可用。

我想对每一个都调用帮助函数。在Ruby中,我可以做一些类似ClassName的事情。方法获取该类上所有可用方法的列表。Python中有类似的东西吗?

例如:

from somemodule import foo
print(foo.methods)  # or whatever is the correct method to call

当前回答

使用inspect模块:

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

还可以查看pydoc模块、交互式解释器中的help()函数和生成所需文档的pydoc命令行工具。您可以只给他们您希望看到的类的文档。例如,它们还可以生成HTML输出并将其写入磁盘。

其他回答

这样就可以了:

dir(module) 

但是,如果您发现阅读返回的列表很烦人,只需使用下面的循环来每行获取一个名称。

for i in dir(module): print i

这将把your_module中定义的所有函数添加到列表中。

result=[]
for i in dir(your_module):
    if type(getattr(your_module, i)).__name__ == "function":
        result.append(getattr(your_module, i))

对于全局函数,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__'
>>>

使用inspect模块:

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

还可以查看pydoc模块、交互式解释器中的help()函数和生成所需文档的pydoc命令行工具。您可以只给他们您希望看到的类的文档。例如,它们还可以生成HTML输出并将其写入磁盘。

Python文档提供了使用内置函数dir的完美解决方案。

您可以只使用dir(module_name),然后它将返回该模块中的函数列表。

例如,dir(time)将返回

[' _STRUCT_TM_ITEMS’,‘__doc__’,‘__loader__’,‘__name__’,‘__package__’,‘__spec__’,‘altzone’,‘asctime’,‘ctime’,‘阳光’,‘get_clock_info’,‘gmtime’,‘作用’,‘mktime’,‘单调’,‘monotonic_ns’,‘perf_counter’,‘perf_counter_ns’,‘process_time’,‘process_time_ns’,‘睡眠’,‘strftime’,‘strptime’,‘struct_time’,‘时间’,‘time_ns’,“时区”,“tzname”,“tzset”)

它是'time'模块包含的函数列表。