有没有方法从Python解释器查看函数、类或模块的源代码?

8 投票
2 回答
6746 浏览
提问于 2025-04-16 00:35

有没有办法在Python解释器中查看一个函数、类或模块的源代码?(除了用help查看文档和用dir查看属性/方法之外)

2 个回答

19

如果你打算用Python进行交互式编程,ipython是个很不错的选择。你可以用%psource这个命令来查看任何已知函数的源代码。

In [1]: import ctypes
In [2]: %psource ctypes.c_bool
class c_bool(_SimpleCData):
_type_ = "?"

输出的内容还会有颜色,方便阅读。你也可以直接用%edit命令打开定义这个函数的源文件,使用你喜欢的编辑器。

In [3]: %edit ctypes.c_bool
11
>>> import inspect
>>> print(''.join(inspect.getsourcelines(inspect.getsourcelines)[0]))
def getsourcelines(object):
    """Return a list of source lines and starting line number for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a list of the lines
    corresponding to the object and the line number indicates where in the
    original source file the first line of code was found.  An IOError is
    raised if the source code cannot be retrieved."""
    lines, lnum = findsource(object)

    if ismodule(object): return lines, 0
    else: return getblock(lines[lnum:]), lnum + 1

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答