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

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

例如:

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

当前回答

对于你不想评估的代码,我推荐一种基于ast的方法(就像csl的答案),例如:

import ast

source = open(<filepath_to_parse>).read()
functions = [f.name for f in ast.parse(source).body
             if isinstance(f, ast.FunctionDef)]

对于其他一切,inspect模块是正确的:

import inspect

import <module_to_inspect> as module

functions = inspect.getmembers(module, inspect.isfunction)

这给出了一个形式为[(<name:str>, <value:function>),…]的二元组列表。

上面的简单答案在各种回应和评论中都有暗示,但没有明确地指出来。

其他回答

您可以使用dir(module)查看所有可用的方法/属性。也可以看看PyDocs。

一旦你导入了模块,你可以这样做:

help(modulename)

... 以交互方式一次性获得所有函数的文档。或者你可以用:

dir(modulename)

... 简单地列出模块中定义的所有函数和变量的名称。

除了之前的回答中提到的dir(模块)或help(模块),还可以尝试: -打开ipython - import module_name - type module_name,按tab键。它会打开一个小窗口,列出python模块中的所有函数。 看起来很整洁。

下面是hashlib模块的所有函数的代码片段

(C:\Program Files\Anaconda2) C:\Users\lenovo>ipython
Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import hashlib

In [2]: hashlib.
             hashlib.algorithms            hashlib.new                   hashlib.sha256
             hashlib.algorithms_available  hashlib.pbkdf2_hmac           hashlib.sha384
             hashlib.algorithms_guaranteed hashlib.sha1                  hashlib.sha512
             hashlib.md5                   hashlib.sha224

你可以使用下面的方法从shell中获取模块中的所有函数:

导入模块

module.*?

使用检查。Getmembers用于获取模块中的所有变量/类/函数等,并传入inspect。Isfunction作为谓词,只得到函数:

from inspect import getmembers, isfunction
from my_project import my_module
    
functions_list = getmembers(my_module, isfunction)

Getmembers返回一个元组列表(object_name, object),按名字的字母顺序排序。

你可以用inspect模块中的任何其他isXXX函数替换isfunction。