从函数获取文档字符串


183

我有以下功能:

def my_func():
    """My docstring is both funny and informative"""
    pass

如何获得文档字符串?


13
请注意,使用-OO运行Python会删除文档字符串。如果您打算将代码分发给其他人,请记住他们可能会以这种方式运行它。如果您的代码依赖于文档字符串,那么这将使那些人真的很不高兴,但不会发现不存在的情况。
DNS

Answers:


243

可以交互地显示

help(my_func)

或者从代码中,您可以使用

my_func.__doc__

1
顺便说一句:这项技术适用于内置函数以及模块和类(也可以对对象测试help()-也可能适用)。这使您的python shell成为交互式帮助shell!
达伦·托马斯

3
在ipython提示符下,您可以执行my_func?并且还会显示文档字符串。
罗纳克

1
help(func)提供可读的输出,而func .__ doc__提供内联输出。感谢你的回答。
imsrgadich


7

在ipython或jupyter笔记本上,您可以使用上述所有方式,但是我同意

my_func?

要么

?my_func

快速概述方法签名和文档字符串。

我避免使用

my_func??

(如@rohan所评论)以docstring,仅用于检查源代码

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.