在 Python 中打印模块或函数的文档字符串
使用 __doc__
属性打印模块的文档字符串,例如 print(my_module.__doc__)
。 如果我们需要打印当前模块的文档字符串,请使用 __doc__
全局变量,例如 print(__doc__)
。
"""
This module's docstring.
"""
import functools
# functools.py - Tools for working with functions and callable objects
print(functools.__doc__)
# 👇️ This module's docstring.
print(__doc__)
我们使用了 __doc__
属性来打印文件的文档字符串。
__doc__
属性返回模块或函数的文档字符串,如果没有文档字符串则返回 None。
如果我们需要打印当前模块的文档字符串,请使用 __doc__
全局变量。
"""
This module's docstring.
"""
# 👇️ This module's docstring.
print(__doc__)
如果我们需要打印内置或第三方模块的文档字符串,请使用模块的 __doc__
属性。
import functools
# functools.py - Tools for working with functions and callable objects
print(functools.__doc__)
我们还可以访问模块中的特定方法并打印其文档字符串。
import functools
# partial(func, *args, **keywords) - new function with partial application
# of the given arguments and keywords.
print(functools.partial.__doc__)
如果我们需要以交互模式打印模块的简短文档,请使用 help()
函数。
import functools
print(help(functools))
要以交互模式打印当前模块的简短文档,请使用 __name__
全局变量。
"""
This module's docstring.
"""
print(help(__name__))
我们还可以使用 __doc__
属性打印函数的文档字符串。
在 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
# Returns the sum of two numbers.
# 25
print(do_math(10, 15))
# 👇️ Returns the sum of two numbers.
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__)
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。