在 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__)

在 Python 中打印函数的文档字符串

我们使用 __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__)