在 Python 中打印函数的文档字符串
使用 __doc__
属性打印函数的文档字符串,例如 print(my_function.__doc__)
。 __doc__
属性返回函数的文档字符串。
def do_math(a, b):
"""Returns the sum of two numbers."""
print(do_math.__doc__)
return a + b
# 25
print(do_math(10, 15))
print(do_math.__doc__)
我们使用 __doc__ 属性来打印函数的文档字符串。
__doc__ 属性返回函数的文档字符串,如果函数没有文档字符串,则返回 None。
def do_math(a, b):
"""Returns the sum of two numbers."""
# ?️ print docstring from inside of a function
print(do_math.__doc__)
return a + b
print(do_math.__doc__) # ?️ Returns the sum of two numbers.
# -------------------------------------
# ?️ without docstring
def example():
pass
print(example.__doc__) # ?️ None
如果需要从函数内部打印函数的文档字符串,也可以使用 __doc__ 属性。
如果我们需要在交互模式下打印函数的文档字符串,请使用 help() 函数。
def do_math(a, b):
"""Returns the sum of two numbers."""
return a + b
# Help on function do_math in module __main__:
# do_math(a, b)
# Returns the sum of two numbers.
# (END)
print(help(do_math))
__doc__ 属性还可用于打印我们导入的函数和方法的文档字符串。
from functools import partial
# partial(func, *args, **keywords) - new function with partial application
# of the given arguments and keywords.
print(partial.__doc__)
可以使用相同的方法打印我们导入的整个模块的文档字符串。
import functools
# functools.py - Tools for working with functions and callable objects
print(functools.__doc__)
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。