我一直在寻找答案很长时间了。假设我用 python 编写了一个函数,并简要说明了该函数的作用。有没有办法从 main 中打印函数的文档?还是从函数本身?
您可以使用help()或打印__doc__. help()打印更详细的对象描述,同时只__doc__保存您在函数开头用三引号定义的文档字符串。""" """
例如,__doc__在sum内置函数上显式使用:
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.
Run Code Online (Sandbox Code Playgroud)
此外,由于 Python 首先编译一个对象并在执行期间对其进行评估,因此您可以__doc__在函数中毫无问题地调用:
def foo():
"""sample doc"""
print(foo.__doc__)
foo() # prints sample doc
Run Code Online (Sandbox Code Playgroud)
请记住,除了函数之外,模块和类都有一个__doc__属性来保存它们的文档。
或者,使用help()for sum:
help(sum)
Run Code Online (Sandbox Code Playgroud)
将打印:
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.
Run Code Online (Sandbox Code Playgroud)
提供了更多信息,包括文档字符串。
| 归档时间: |
|
| 查看次数: |
4318 次 |
| 最近记录: |