我现在很多时间都在寻找答案。让我们说我在python中编写了一个函数,并简要介绍了这个函数的用途。有没有办法从main中打印功能的文档?或者从功能本身?
答案 0 :(得分:3)
您可以使用 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.
此外,由于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.
提供更多信息,包括docstring。