飞翔飞翔
主页
  • 计算机基础

    • TCP/IP协议
    • Linux命令
  • 数据库

    • SQL教程
  • 编程语言

    • C语言
    • Python2
    • Python3
  • 数据格式

    • JSON教程
  • 工具

    • Markdown指南
  • Git

    • GitFlow
  • Quartz

    • Quartz教程
  • Java

    • Java设计模式
  • 缓存

    • Redis教程
联系
阿里云
主页
  • 计算机基础

    • TCP/IP协议
    • Linux命令
  • 数据库

    • SQL教程
  • 编程语言

    • C语言
    • Python2
    • Python3
  • 数据格式

    • JSON教程
  • 工具

    • Markdown指南
  • Git

    • GitFlow
  • Quartz

    • Quartz教程
  • Java

    • Java设计模式
  • 缓存

    • Redis教程
联系
阿里云
  • 学习路径
  • 第1章 认识Python

    • Python 历史与特点
    • Python 2 与 Python 3 的核心差异
    • 安装与运行 Python 2.7.18
    • 编码规范 PEP 8
  • 第2章 基础语法

    • 变量与对象
    • 数字类型
    • 字符串 str
    • Unicode 字符串
    • 运算符
    • 空值 None
  • 第3章 流程控制

    • if 条件语句
    • if-else 条件语句
    • if-elif-else 多分支
    • 条件表达式(三元运算符)
    • while 循环
    • for 循环
    • range 与 xrange
    • 循环控制:break、continue、pass
    • 循环 else 子句
  • 第4章 数据结构

    • 列表基础
    • 列表方法
    • 列表推导式
    • 元组
    • 字典基础
    • 字典方法
    • 字典循环技巧
    • 集合
    • 序列解包
    • 序列比较
  • 第5章 函数

    • 定义函数
    • 参数传递机制
    • 默认参数
    • 关键字参数
    • 可变参数
    • Lambda 表达式
    • 文档字符串
    • 函数对象
  • 第6章 模块与包

    • import 导入
    • 模块搜索路径
    • name 与主程序
    • 编译文件 .pyc 与 .pyo
    • 包结构
    • dir() 函数
  • 第7章 文件与IO

    • 打开与关闭文件
    • 文件读写方法
    • with 上下文管理器
    • 格式化输出:% 操作符
    • 格式化输出:str.format()
    • JSON 序列化
  • 第8章 面向对象

    • 类定义与实例化
    • init 构造方法
    • 类变量与实例变量
    • 方法调用与 self
    • 继承基础
    • 多重继承
    • 新式类与旧式类
    • 私有变量与名称改写
    • 属性装饰器 property
    • 类方法与静态方法
    • 魔术方法
    • 空类与数据记录
  • 第9章 异常处理

    • 异常类型
    • try-except
    • try-except-else-finally
    • 抛出异常 raise
    • 自定义异常
    • with 语句与上下文管理器
  • 第10章 迭代器与生成器

    • 迭代器协议
    • 生成器函数
    • 生成器表达式
    • itertools模块
  • 第11章 标准库精要

    • os模块
    • sys模块
    • datetime模块
    • re模块
    • json模块
    • collections模块
    • math与random模块
    • urllib2与网络请求
    • subprocess与命令执行
    • threading与并发
    • unittest与测试
    • 虚拟环境与包管理
  • 第12章 工程实践

    • 调试技巧
    • 性能分析
    • 文档与注释
    • 下一步学习

文档与注释

良好的文档和注释是代码可维护性的基础。Python 2.7 通过文档字符串(docstring)、注释、类型提示(有限支持)和代码风格规范,帮助开发者写出清晰易懂的代码。

文档字符串 Docstring

模块、类、函数的文档用三引号字符串写在定义的第一行:

def calculate_area(length, width):
    """Calculate the area of a rectangle.
    
    Args:
        length (float): The length of the rectangle.
        width (float): The width of the rectangle.
    
    Returns:
        float: The area (length * width).
    
    Raises:
        ValueError: If length or width is negative.
    
    Examples:
        >>> calculate_area(5, 3)
        15.0
        >>> calculate_area(0, 10)
        0.0
    """
    if length < 0 or width < 0:
        raise ValueError("Dimensions must be non-negative")
    return length * width

访问文档字符串:

print calculate_area.__doc__
help(calculate_area)        # 更友好的格式化输出

模块级文档:

"""String utilities for text processing.

This module provides functions for common string operations
including formatting, validation, and transformation.

Usage:
    import string_utils
    result = string_utils.capitalize_words("hello world")
"""

import re

def capitalize_words(text):
    """Capitalize the first letter of each word."""
    return re.sub(r'\b\w', lambda m: m.group().upper(), text)

注释

注释解释"为什么",代码解释"做什么":

# 好的注释:解释意图和原因
# 使用二分查找因为数据已排序且量大
index = binary_search(sorted_data, target)

# 坏的注释:重复代码
# 将 x 加 1
x = x + 1

# 好的注释:标记待办
# TODO: 处理边界情况 n=0
# FIXME: 当前实现 O(n^2),需要优化
# NOTE: 这个算法假设输入已排序
# HACK: 临时方案,需要重构

行内注释:

x = x + 1       # 补偿边界偏移

行内注释应简洁,放在代码右侧,与代码之间至少两个空格。

PEP 257 文档字符串规范

PEP 257 定义了文档字符串的编写规范:

  • 所有公共模块、函数、类、方法都需要 docstring
  • 非公共方法也需要 docstring,说明作用
  • 第一行是简短摘要,以句号结尾
  • 第二行空行
  • 后续行详细说明
class BankAccount(object):
    """A simple bank account implementation.
    
    Supports deposits, withdrawals, and balance inquiries.
    Does not handle interest or fees.
    """
    
    def __init__(self, initial_balance=0):
        """Initialize account with optional starting balance.
        
        Args:
            initial_balance (int, optional): Starting balance. Defaults to 0.
        """
        self.balance = initial_balance
    
    def deposit(self, amount):
        """Add funds to the account.
        
        Args:
            amount (int): Amount to deposit. Must be positive.
        
        Returns:
            int: New balance after deposit.
        """
        self.balance += amount
        return self.balance

生成文档

pydoc:Python 内置文档生成工具

python -m pydoc mymodule          # 查看模块文档
python -m pydoc -p 8080           # 启动 HTTP 文档服务器

Sphinx:专业的文档生成工具(需安装)

pip install sphinx
sphinx-quickstart docs/           # 初始化文档项目

Sphinx 支持 reStructuredText 格式,可以从 docstring 自动生成 API 文档。

代码可读性

命名规范:

类型规范示例
模块小写,下划线my_module.py
包小写,无下划线mypackage
类大写驼峰BankAccount
函数/方法小写,下划线calculate_area
常量大写,下划线MAX_SIZE
私有下划线前缀_internal_func

函数长度:

一个函数应该只做一件事。如果函数超过 20 行,考虑拆分:

# 不好的:一个函数做太多事
def process_user_data(data):
    # 验证
    if not data:
        return None
    # 清洗
    cleaned = data.strip().lower()
    # 转换
    converted = int(cleaned)
    # 存储
    save_to_db(converted)
    # 通知
    send_notification(converted)
    return converted

# 好的:拆分为小函数
def validate_data(data):
    return data.strip().lower() if data else None

def parse_user_id(data):
    return int(data)

def process_user_data(data):
    cleaned = validate_data(data)
    if not cleaned:
        return None
    user_id = parse_user_id(cleaned)
    save_to_db(user_id)
    send_notification(user_id)
    return user_id

实际应用

项目 README:

# MyProject

A brief description of what this project does.

## Installation

```bash
pip install -r requirements.txt

Usage

from myproject import Client

client = Client(api_key="your-key")
result = client.query("example")

API Reference

See docs/api.md for detailed documentation.


**CHANGELOG**:

```markdown
# Changelog

## 1.1.0 (2024-01-15)
- Added support for batch operations
- Fixed memory leak in long-running processes

## 1.0.0 (2024-01-01)
- Initial release

文档驱动开发

先写文档,再写代码:

  1. 定义函数签名和 docstring
  2. 写测试验证 docstring 中的示例
  3. 实现函数使测试通过
def parse_date(date_string):
    """Parse ISO format date string.
    
    Args:
        date_string (str): Date in 'YYYY-MM-DD' format.
    
    Returns:
        datetime.date: Parsed date object.
    
    Raises:
        ValueError: If format is invalid.
    
    Examples:
        >>> parse_date('2024-01-15')
        datetime.date(2024, 1, 15)
        >>> parse_date('invalid')
        Traceback (most recent call last):
            ...
        ValueError: Invalid date format
    """
    # 实现...
    pass

文档中的 >>> 示例可以用 doctest 模块自动测试:

python -m doctest mymodule.py -v
上一页
性能分析
下一页
下一步学习