迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

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

作者:迹忆客 最近更新:2023/01/07 浏览次数:

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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便