python - 如何打印函数的文档 python

标签 python printing

<分区>

我一直在寻找答案很长时间了。假设我在 python 中编写了一个函数,并对该函数的作用做了一个简短的文档说明。有什么方法可以从 main 中打印函数的文档吗?还是来自函数本身?

最佳答案

您可以使用 help() 或打印 __doc__help() 打印对象的更详细描述,而 __doc__ 保存 您用三重引号定义的文档字符串 """""" 在函数的开头

例如,在 sum 内置函数上显式使用 __doc__:

print(sum.__doc__)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.

此外,由于 Python 首先编译一个对象并在执行期间评估它,您可以在函数内调用 __doc__ 没有问题:

def foo():
    """sample doc"""
    print(foo.__doc__)

foo()  # prints sample doc

请记住,除了函数之外,模块和类还有一个 __doc__ 属性来保存它们的文档。

或者,使用help()sum:

help(sum)

将打印:

Help on built-in function sum in module builtins:

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

提供更多信息,包括文档字符串。

关于python - 如何打印函数的文档 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34277363/

相关文章:

python fedex api问题

python - pd.series.str.pad() 返回 NaN

pdf - 使用utf8编码将文本转换为pdf(替代a2ps)

css - 哪种可打印元素比线性渐变更好用?

Python:在二维数组中查找所有可能的唯一双索引组合

python - 从列表中提取时间值并添加到新列表或数组

python - Qhull 凸包要求我输入至少 3 个点

python - 在 Python 中,刷新是如何工作的,原因是什么?

windows - Delphi - 应用程序主窗体的焦点不正确

python - 为什么 Python 3.11 在 print(set[0]) 处不抛出错误?