主页
  • 主页
  • 分类
  • 热文
  • 教程
  • 面试
  • 标签
Python

Python 基础

Python 主页
Python 概述
Python 历史
Python 功能
Python 与 C++
Python Hello World
Python 应用领域
Python 解释器及其模式
Python 环境设置
Python 虚拟环境
Python 语法
Python 变量
Python 数据类型
Python 类型转换
Python Unicode 系统
Python 文字
Python 运算符
Python 算术运算符
Python 比较运算符
Python 赋值运算符
Python 逻辑运算符
Python 位运算符
Python 成员运算符
Python 身份运算符
Python 运算符优先级
Python 注释
Python 用户输入
Python 数字
Python 布尔值

Python 控制语句

Python 控制流
Python 决策
Python if 语句
Python if-else 语句
Python 嵌套 if 语句
Python match-case 语句
Python 循环
Python For 循环
Python for-else 循环
Python while 循环
Python break 语句
Python Continue 语句
Python pass 语句
Python 嵌套循环

Python 函数和模块

Python 函数
Python 默认参数
Python 关键字参数
Python 关键字专用参数
Python 位置参数
Python 仅限位置参数
Python 任意或可变长度参数
Python 变量作用域
Python 函数注释
Python 模块
Python 内置函数

Python 字符串

Python 字符串
Python 字符串切片
Python 字符串修改
Python 字符串连接
Python 字符串格式化
Python 转义字符
Python 字符串方法
Python 字符串练习

Python 列表

Python 列表
Python 访问列表项
Python 更改列表项
Python 添加列表项
Python 删除列表项
Python 循环列表
Python 列表推导式
Python 排序列表
Python 复制列表
Python 合并列表
Python 列表方法
Python 列表练习

Python 元组

Python 元组
Python 访问元组项
Python 更新元组
Python 解包元组项
Python 循环元组
Python 合并元组
Python 元组方法
Python 元组练习

Python 集合

Python 集合
Python 访问集合项
Python 添加集合项
Python 删除集合项
Python 循环集合
Python 合并集合
Python 复制集合
Python 集合运算符
Python 集合方法
Python 集合练习

Python 字典

Python 字典
Python 访问字典项
Python 更改字典项
Python 添加字典项
Python 移除字典项
Python 字典视图对象
Python 循环字典
Python 复制字典
Python 嵌套字典
Python 字典方法
Python 字典练习

Python 数组

Python 数组
Python 访问数组项
Python 添加数组项
Python 移除数组项
Python 循环数组
Python 复制数组
Python 反转数组
Python 排序数组
Python 合并数组
Python 数组方法
Python 数组练习

Python 文件处理

Python 文件处理
Python 文件写入
Python 文件读取
Python 重命名和删除文件
Python 目录
Python 文件方法
Python 文件/目录方法
Python OS.Path 方法

Python 面向对象编程

Python OOP 概念
Python 类和对象
Python 类属性
Python 类方法
Python 静态方法
Python 构造函数
Python 访问修饰符
Python 继承
Python 多态
Python 方法重写
Python 方法重载
Python 动态绑定
Python 动态类型
Python 抽象
Python 封装
Python 接口
Python 包
Python 内部类
Python 匿名类和对象
Python 单例类
Python 包装器类
Python 枚举
Python 反射

Python 错误和异常

Python 语法错误
Python 异常处理
Python Try-Except
Python Try-Finally
Python 抛出异常
Python 异常链
Python 嵌套 try
Python 用户定义异常
Python 日志记录
Python 断言
Python 内置异常

Python 多线程

Python 多线程
Python 线程生命周期
Python 创建线程
Python 启动线程
Python 合并线程
Python 命名线程
Python 线程调度
Python 线程池
Python 主线程
Python 线程优先级
Python 守护线程
Python 线程同步

Python 同步

Python 线程间通信
Python 死锁
Python 中断线程

Python 网络

Python 网络编程
Python 套接字编程
Python URL 处理
Python 泛型

Python 杂项

Python Date and Time
Python math模块
Python 迭代器
Python 生成器
Python 闭包
Python 装饰器
Python 递归
Python 正则表达式
Python Pip
Python 数据库访问
Python 弱引用
Python 序列化
Python 模板技术
Python 输出格式化
Python 性能测量
Python 数据压缩
Python 通用网关接口
Python XML 处理
Python 用户界面(GUI)
Python 命令行参数
Python Docstrings
Python JSON
Python 发送电子邮件
Python 进一步扩展
Python 工具/实用程序
Python GUI

Python 高级概念

Python 抽象基类
Python 自定义异常
Python 高阶函数
Python 对象的内部机制
Python 内存管理
Python 元类
Python 元编程
Python 模拟与桩
Python 猴子补丁
Python 信号处理
Python 类型提示
Python 进行自动化
Python Humanize包
Python 上下文管理器
Python 协程
Python 描述符
Python 内存泄漏
Python 不可变数据结构

基础

Python 主页
Python 概述
Python 历史
Python 功能
Python 与 C++
Python Hello World
Python 应用领域
Python 解释器及其模式
Python 环境设置
Python 虚拟环境
Python 语法
Python 变量
Python 数据类型
Python 类型转换
Python Unicode 系统
Python 文字
Python 运算符
Python 算术运算符
Python 比较运算符
Python 赋值运算符
Python 逻辑运算符
Python 位运算符
Python 成员运算符
Python 身份运算符
Python 运算符优先级
Python 注释
Python 用户输入
Python 数字
Python 布尔值

控制语句

Python 控制流
Python 决策
Python if 语句
Python if-else 语句
Python 嵌套 if 语句
Python match-case 语句
Python 循环
Python For 循环
Python for-else 循环
Python while 循环
Python break 语句
Python Continue 语句
Python pass 语句
Python 嵌套循环

函数和模块

Python 函数
Python 默认参数
Python 关键字参数
Python 关键字专用参数
Python 位置参数
Python 仅限位置参数
Python 任意或可变长度参数
Python 变量作用域
Python 函数注释
Python 模块
Python 内置函数

字符串

Python 字符串
Python 字符串切片
Python 字符串修改
Python 字符串连接
Python 字符串格式化
Python 转义字符
Python 字符串方法
Python 字符串练习

列表

Python 列表
Python 访问列表项
Python 更改列表项
Python 添加列表项
Python 删除列表项
Python 循环列表
Python 列表推导式
Python 排序列表
Python 复制列表
Python 合并列表
Python 列表方法
Python 列表练习

元组

Python 元组
Python 访问元组项
Python 更新元组
Python 解包元组项
Python 循环元组
Python 合并元组
Python 元组方法
Python 元组练习

集合

Python 集合
Python 访问集合项
Python 添加集合项
Python 删除集合项
Python 循环集合
Python 合并集合
Python 复制集合
Python 集合运算符
Python 集合方法
Python 集合练习

字典

Python 字典
Python 访问字典项
Python 更改字典项
Python 添加字典项
Python 移除字典项
Python 字典视图对象
Python 循环字典
Python 复制字典
Python 嵌套字典
Python 字典方法
Python 字典练习

数组

Python 数组
Python 访问数组项
Python 添加数组项
Python 移除数组项
Python 循环数组
Python 复制数组
Python 反转数组
Python 排序数组
Python 合并数组
Python 数组方法
Python 数组练习

文件处理

Python 文件处理
Python 文件写入
Python 文件读取
Python 重命名和删除文件
Python 目录
Python 文件方法
Python 文件/目录方法
Python OS.Path 方法

面向对象编程

Python OOP 概念
Python 类和对象
Python 类属性
Python 类方法
Python 静态方法
Python 构造函数
Python 访问修饰符
Python 继承
Python 多态
Python 方法重写
Python 方法重载
Python 动态绑定
Python 动态类型
Python 抽象
Python 封装
Python 接口
Python 包
Python 内部类
Python 匿名类和对象
Python 单例类
Python 包装器类
Python 枚举
Python 反射

错误和异常

Python 语法错误
Python 异常处理
Python Try-Except
Python Try-Finally
Python 抛出异常
Python 异常链
Python 嵌套 try
Python 用户定义异常
Python 日志记录
Python 断言
Python 内置异常

多线程

Python 多线程
Python 线程生命周期
Python 创建线程
Python 启动线程
Python 合并线程
Python 命名线程
Python 线程调度
Python 线程池
Python 主线程
Python 线程优先级
Python 守护线程
Python 线程同步

同步

Python 线程间通信
Python 死锁
Python 中断线程

网络

Python 网络编程
Python 套接字编程
Python URL 处理
Python 泛型

杂项

Python Date and Time
Python math模块
Python 迭代器
Python 生成器
Python 闭包
Python 装饰器
Python 递归
Python 正则表达式
Python Pip
Python 数据库访问
Python 弱引用
Python 序列化
Python 模板技术
Python 输出格式化
Python 性能测量
Python 数据压缩
Python 通用网关接口
Python XML 处理
Python 用户界面(GUI)
Python 命令行参数
Python Docstrings
Python JSON
Python 发送电子邮件
Python 进一步扩展
Python 工具/实用程序
Python GUI

高级概念

Python 抽象基类
Python 自定义异常
Python 高阶函数
Python 对象的内部机制
Python 内存管理
Python 元类
Python 元编程
Python 模拟与桩
Python 猴子补丁
Python 信号处理
Python 类型提示
Python 进行自动化
Python Humanize包
Python 上下文管理器
Python 协程
Python 描述符
Python 内存泄漏
Python 不可变数据结构

Python Docstrings


上一章 下一章

在 Python 中,docstrings 是一种用于记录模块、类、函数和方法的方法。它们写在三引号(""" """ 或 ''' ''')之间,并可以跨越多行。

Docstrings 作为一种方便的方式,将文档与 Python 代码关联起来。它们可以通过相应 Python 对象的 __doc__ 属性进行访问。下面是在 Python 中编写 docstrings 的不同方式:

单行 Docstrings

单行 docstrings 用于简短且简单的文档记录。它们提供了一个函数或方法作用的简明描述。单行 docstrings 应该在三引号内写在一行为宜,并以句点结束。

示例

在下面的例子中,我们使用单行 docstring 来写一段文本:

def add(a, b):
   """Return the sum of two numbers."""
   return a + b

result = add(5, 3)
print("Sum:", result)

多行 Docstrings

多行 docstrings 用于更详细的文档记录。它们提供了更全面的描述,包括参数、返回值和其他相关信息。多行 docstrings 开始和结束于三引号,并包含一个摘要行接着是一个空行以及更详细的描述。

示例

下面的例子使用了多行 docstrings 作为代码的解释:

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)

模块的 Docstrings

当为模块编写 docstrings 时,将 docstring 放在模块顶部,在任何导入语句之后。模块 docstring 提供了模块功能的概览,并列出了模块提供的主要组件,如函数、类和异常。

示例

在这个例子中,我们展示了在 Python 中使用模块 docstrings:

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")

类的 Docstrings

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

示例

在下面的例子中,我们展示了 Python 中类 docstrings 的使用:

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

访问 Docstrings

Python 中的 docstrings 可以通过它们所记录的对象的 __doc__ 属性来访问。这个属性包含了与对象相关联的文档字符串(docstring),提供了一种访问和展示有关函数、类、模块或方法的目的和用途的信息的方式。

示例

在下面的例子中,我们定义了两个函数,“add” 和 “multiply”,每个函数都有一个描述其参数和返回值的 docstring。然后我们使用 __doc__ 属性来访问并打印这些 docstrings:

# 定义一个带有 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)

# 定义另一个带有 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)

# 访问 docstrings
print(add.__doc__)
print(multiply.__doc__)

编写 Docstrings 的最佳实践

以下是编写 Python docstrings 的最佳实践:

  • 清晰简洁:确保 docstring 清晰解释代码的目的和用途,避免不必要的细节。
  • 正确语法和拼写:确保 docstring 书写良好,语法和拼写正确。
  • 遵循约定:使用标准格式化 docstrings 的约定,如 Google 样式、NumPy 样式或 Sphinx 样式。
  • 包含示例:在适用的地方提供示例来说明如何使用所记录的代码。

Google 样式 Docstring

Google 样式 docstrings 提供了一种结构化的方式来记录 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 样式 Docstring

NumPy/SciPy 样式的 docstrings 在科学计算中很常见。它们包括参数、返回值和示例的部分。

示例

下面是一个带有 NumPy/SciPy 样式 docstring 的函数示例:

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)

Sphinx 样式 Docstring

Sphinx 样式 docstrings 与 Sphinx 文档生成器兼容,并使用 reStructuredText 格式。

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

示例

下面是一个带有 Sphinx 样式 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)

Docstring 与注释的区别

下面列出了 Python docstrings 与注释之间的区别,重点在于它们的目的、格式、用途和可访问性:

Docstring 注释
用于记录 Python 对象,如函数、类、方法、模块或包。 用于注释代码给人阅读,提供上下文,或暂时禁用代码。
写在三引号(""" """ 或 ''' ''')内,并紧接对象定义之后。 以 # 符号开头,并放在被注释代码的同一行。
作为对象的属性存储并可以程序化访问。 在执行期间被 Python 解释器忽略,纯粹为人理解。
使用对象的 __doc__ 属性访问。 不可程序化访问;仅存在于源代码中。
上一章 下一章
阅读号二维码

关注阅读号

联系二维码

联系我们

© 2024 Yoagoa. All rights reserved.

粤ICP备18007391号

站点地图