news 2026/11/1 23:08:48

Python - 文档字符串

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Python - 文档字符串

Python 中的文档字符串

在 Python 中,docstring 是一种用于文档模块、类、函数和方法的方式。它们以三引号(“”)书写,且可以跨越多行。

文档字符串是将文档与Python代码关联起来的便捷方式。它们可以通过其所记录的 Python 对象的__doc__属性访问。以下是写docstring的不同方式——

单行文件串

单行文档字符串用于简短且简单的文档记录。它们简明地描述了该函数或方法的作用。单行文档字符串应能在三引号内的一行内,并以句号结尾。

示例

在下面的例子中,我们使用单行docstring来写入文本−

def add(a, b): """Return the sum of two numbers.""" return a + b result = add(5, 3) print("Sum:", result)

多行文档字符串

多行文档字符串用于更详细的文档记录。它们提供了更全面的描述,包括参数、返回值及其他相关细节。多行文档以三引号开头和结尾,包含摘要行后接空白行和更详细的描述。

示例

以下示例使用多行文档字符串来解释代码 −

def multiply(a, b): """ Multiply two numbers and return the result. Parameters: a (int or float): The first number. b (int or float): The second number. Returns: int or float: The result of multiplying a and b. """ return a * b result = multiply(5, 3) print("Product:", result)

模块文档字符串

编写模块文档字符串时,将文档字符串放在模块顶部,紧接着导入语句之后。模块文档字符串概述了模块的功能,并列出其主要组件,如函数列表、类和模块提供的异常。

示例

在这个例子中,我们演示了 Python 中 docstring 用于模块的过程 −

import os """ This module provides Utility functions for file handling operations. Functions: - 'read_file(filepath)': Reads and returns the contents of the file. - 'write_file(filepath, content)': Writes content to the specified file. Classes: - 'FileNotFoundError': Raised when a file is not found. Example usage: >>> import file_utils >>> content = file_utils.read_file("example.txt") >>> print(content) 'Hello, world!' >>> file_utils.write_file("output.txt", "This is a test.") """ print("This is os module")

类文档字符串

类可以用文档字符串来描述它们的目的和用途。类内的每个方法也可以有自己的文档字符串。类docstring应提供该类及其方法的概览。

示例

在下面的示例中,我们展示了 Python 中 docstring 用于类的应用 −

class Calculator: """ A simple calculator class to perform basic arithmetic operations. Methods: - add(a, b): Return the sum of two numbers. - multiply(a, b): Return the product of two numbers. """ def add(self, a, b): """Return the sum of two numbers.""" return a + b def multiply(self, a, b): """ Multiply two numbers and return the result. Parameters: a (int or float): The first number. b (int or float): The second number. Returns: int or float: The result of multiplying a and b. """ return a * b cal = Calculator() print(cal.add(87, 98)) print(cal.multiply(87, 98))

访问文档字符串

Python 中的文档字符串是通过其所记录对象的__doc__属性访问的。该属性包含与对象相关的文档字符串(docstring),提供了访问和显示函数、类、模块或方法的目的和用途信息的方式。

示例

在下面的例子中,我们定义了两个函数,“加法”和“乘法”,每个函数都有文档字符串描述其参数和返回值。然后我们使用“__doc__”属性访问并打印这些文档字符串 −

# Define a function with a docstring def add(a, b): """ Adds two numbers together. Parameters: a (int): The first number. b (int): The second number. Returns: int: The sum of a and b. """ return a + b result = add(5, 3) print("Sum:", result) # Define another function with a docstring def multiply(x, y): """ Multiplies two numbers together. Parameters: x (int): The first number. y (int): The second number. Returns: int: The product of x and y. """ return x * y result = multiply(4, 7) print("Product:", result) # Accessing the docstrings print(add.__doc__) print(multiply.__doc__)

文档字符串编写的最佳实践

以下是用 Python 编写文档字符串的最佳实践 −

  • 清晰简洁 −确保文档字符串清楚说明代码的目的和用途,避免不必要的细节。

  • 使用正确的语法和拼写 −确保文档词汇写得好,语法和拼写正确。

  • 遵循约定 −使用文档字符串格式的标准惯例,比如 Google 风格、NumPy 风格或 Sphinx 风格。

  • 包含示例 −在适用的情况下,提供示例说明如何使用文档化的代码。

谷歌样式文档字符串

Google 风格的文档字符串通过缩进和标题提供了一种结构化的方式来记录 Python 代码。它们设计为通俗易读且信息丰富,遵循特定的格式。

示例

以下是带有 Google 风格 docstring 的函数示例 −

def divide(dividend, divisor): """ Divide two numbers and return the result. Args: dividend (float): The number to be divided. divisor (float): The number to divide by. Returns: float: The result of the division. Raises: ValueError: If `divisor` is zero. """ if divisor == 0: raise ValueError("Cannot divide by zero") return dividend / divisor result = divide(4, 7) print("Division:", result)

NumPy/SciPy 风格文档字符串

NumPy/SciPy 风格的文档字符串在科学计算中很常见。它们包含参数、返回和示例的章节。

示例

以下是一个带有 NumPy/SciPy 风格文档字符串的函数示例 −

def fibonacci(n): """ Compute the nth Fibonacci number. Parameters ---------- n : int The index of the Fibonacci number to compute. Returns ------- int The nth Fibonacci number. Examples -------- >>> fibonacci(0) 0 >>> fibonacci(5) 5 >>> fibonacci(10) 55 """ if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) result = fibonacci(4) print("Result:", result)

斯芬克斯风格的Docstring

Sphinx 风格的文档字符串兼容 Sphinx 文档生成器,并使用reStructuredText格式。

reStructuredText(reST)是一种用于创建结构化文本文档的轻量级标记语言。Sphinx 文档生成器以“reStructuredText”文件为输入,生成多种格式的高质量文档,包括 HTML、PDF、ePub 等。

示例

以下是一个带有斯芬克斯式docstring的函数示例 −

def divide(dividend, divisor): """ Divide two numbers and return the result. Args: dividend (float): The number to be divided. divisor (float): The number to divide by. Returns: float: The result of the division. Raises: ValueError: If `divisor` is zero. """ if divisor == 0: raise ValueError("Cannot divide by zero") return dividend / divisor result = divide(76, 37) print("Result:", result)

文档与评论

以下是 Python 文档字符串与注释之间的区别,重点关注它们的用途、格式、用法和可访问性 -

文件串评论
用于文档化 Python 对象,如函数、类、方法、模块或包。用于为人类阅读者注释代码、提供上下文或暂时禁用代码。
书写在三引号内(“”或“'),并紧接对象定义之后。以#符号开始,放置在与带注释代码同一行。
作为对象的属性存储,并可通过程序访问。在执行过程中,Python 解释器会忽略它,纯粹是为了人类理解。
通过对象的__doc__属性访问。无法通过程序访问;仅存在于源代码中。
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/11/1 10:02:16

【Android FrameWork】第三十六天:随机数EntropyMixer

Android EntropyService 在 Android 系统中,EntropyService(后更名为 EntropyMixer) 是保障随机数安全性的核心服务之一。 它通过维护内核熵池(Entropy Pool),解决了系统启动初期随机数可预测的问题&#x…

作者头像 李华
网站建设 2026/11/1 0:39:19

介观交通流仿真软件:VISSIM (介观模式)_(16).高级仿真技术

高级仿真技术 在上一节中,我们介绍了如何使用VISSIM进行基本的交通流仿真设置和运行。本节将深入探讨VISSIM的高级仿真技术,帮助用户在更复杂的交通场景中进行仿真分析。我们将重点介绍以下内容:自定义交通模型、交通事件的动态管理、信号控制…

作者头像 李华
网站建设 2026/11/1 20:36:25

安卓 之 PassthruPatchRecord

1. 类介绍 PassthruPatchRecord 是 Android AudioFlinger 中一个特殊的 patch。它的核心设计目标是实现一种 “直通” 模式,用于 AUDIO_SOURCE_VOICE_PERFORMANCE 等需要极低延迟的音频场景。 • 继承关系: PassthruPatchRecord -> PatchRecord -> RecordTrack ->…

作者头像 李华
网站建设 2026/11/1 11:36:33

YOLOv8 训练与检测系统智慧化交通公路上落石检测数据集 智慧道路交通路面障碍物检测数据集 智慧交通、山区公路监控、应急预警平台 YOLOv8 训练与检测系统

道路落石及障碍物检测数据集【共2套】 第一套: 智慧化道路落石检测数据集 nc一类:shitou1第二套:6类 道路障碍物检测数据集 落石 滑坡检测数据集 6 names: [‘Car’, ‘Motorcycle’, ‘People’, ‘shitou’, ‘Warning-Crash’, ‘landslide’]1111111…

作者头像 李华
网站建设 2026/10/31 19:08:55

基于django智慧农业管理系统设计开发实现

背景分析农业现代化转型需求日益迫切,传统农业依赖人工经验、资源利用率低、环境监测滞后等问题突出。全球气候变化加剧、人口增长导致的粮食安全压力,推动农业向精准化、数据化方向发展。物联网(IoT)、大数据、人工智能等技术的成…

作者头像 李华
网站建设 2026/10/31 19:01:19

Android架构师面试指南:基于跨越速运职位要求的全面解析与参考答案

跨越速运 Android架构师 职位描述 架构设计/优化Android客户端产品研发架构设计能力Kotlin 1、负责Android客户端的应用架构设计和承担核心功能代码编写; 2、负责设计模块与模块间及与第三方模块代码之间高效解耦方案; 3、负责参与产品需求分析并参与技术实施方案设计; 4、负责…

作者头像 李华