网站首页 > 技术文章 正文
23.1 代码规范与风格
23.1.1 PEP8规范要点
23.1.2 自动化检查工具
# 安装检查工具
pip install flake8 pylint black
# 运行检查
flake8 project_dir/
pylint module.py
black --check project_dir/
23.2 单元测试
23.2.1 unittest框架
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertNotEqual(add(0.1, 0.2), 0.3) # 浮点精度问题
def test_add_types(self):
with self.assertRaises(TypeError):
add("2", 3)
if __name__ == '__main__':
unittest.main()
23.2.2 pytest高级特性
# test_math.py
import pytest
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(0.1, 0.2, pytest.approx(0.3)),
(-1, 1, 0)
])
def test_add(a, b, expected):
from math_utils import add
assert add(a, b) == expected
# 运行测试: pytest -v test_math.py
23.3 文档生成
23.3.1 docstring规范
def calculate_interest(principal, rate, years):
"""计算复利
Args:
principal (float): 本金
rate (float): 年利率(0-1之间)
years (int): 投资年限
Returns:
float: 最终金额
Raises:
ValueError: 当利率不在0-1范围时抛出
"""
if not 0 <= rate <= 1:
raise ValueError("利率必须在0到1之间")
return principal * (1 + rate) ** years
23.3.2 Sphinx文档
# 初始化文档项目
sphinx-quickstart docs
# 配置conf.py
extensions = ['sphinx.ext.autodoc']
autodoc_default_options = {
'members': True,
'special-members': '__init__'
}
# 生成API文档
sphinx-apidoc -o docs/source mypackage
make html
23.4 日志管理
23.4.1 logging配置
import logging
from logging.handlers import RotatingFileHandler
def setup_logger():
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 控制台Handler
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# 文件Handler(自动轮转)
file = RotatingFileHandler(
'app.log', maxBytes=1e6, backupCount=3
)
file.setLevel(logging.DEBUG)
# 格式化
fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(fmt)
console.setFormatter(formatter)
file.setFormatter(formatter)
# 添加Handler
logger.addHandler(console)
logger.addHandler(file)
return logger
logger = setup_logger()
logger.info("系统初始化完成")
23.5 项目结构
23.5.1 标准项目布局
myproject/
├── docs/ # 文档
├── tests/ # 测试代码
├── src/ # 源代码
│ ├── mypackage/ # 主包
│ │ ├── __init__.py
│ │ ├── module1.py
│ │ └── module2.py
│ └── scripts/ # 可执行脚本
├── .gitignore
├── pyproject.toml # 构建配置
├── README.md
└── requirements.txt # 依赖列表
23.5.2 模块化设计原则
- 单一职责:每个模块/类只做一件事
- 低耦合高内聚:模块间依赖最小化
- 明确接口:通过__all__暴露公共API
- 分层架构:分离业务逻辑与基础设施
23.6 打包与发布
23.6.1 项目打包配置
# pyproject.toml
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "mypackage"
version = "1.0.0"
authors = [{name = "Your Name", email = "you@example.com"}]
description = "A sample Python package"
readme = "README.md"
requires-python = ">=3.8"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
]
[project.urls]
Homepage = "https://github.com/you/mypackage"
23.6.2 发布到PyPI
# 构建包
python -m build
# 检查包
twine check dist/*
# 上传到PyPI
twine upload dist/*
23.7 应用举例
案例1:项目模板
# src/mypackage/core.py
"""核心业务逻辑实现"""
import logging
from typing import List
logger = logging.getLogger(__name__)
class DataProcessor:
"""数据处理引擎"""
def __init__(self, config: dict):
self.config = config
self._setup()
def _setup(self):
"""初始化资源"""
logger.debug("初始化数据处理引擎")
# 初始化代码...
def process(self, items: List[float]) -> List[float]:
"""处理数据并返回结果"""
if not items:
logger.warning("收到空输入列表")
return []
try:
result = [x * self.config['factor'] for x in items]
logger.info(f"处理完成,共{len(result)}条数据")
return result
except Exception as e:
logger.error(f"处理失败: {str(e)}")
raise
# tests/test_core.py
import pytest
from mypackage.core import DataProcessor
class TestDataProcessor:
@pytest.fixture
def processor(self):
return DataProcessor({'factor': 2})
def test_process(self, processor):
assert processor.process([1, 2, 3]) == [2, 4, 6]
def test_empty_input(self, processor, caplog):
result = processor.process([])
assert result == []
assert "收到空输入列表" in caplog.text
案例2:CI/CD集成
# .github/workflows/ci.yml
name: Python CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10"]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest pytest-cov
pip install -e .
- name: Lint with flake8
run: flake8 src tests
- name: Run tests
run: pytest --cov=src --cov-report=xml tests/
- name: Upload coverage
uses: codecov/codecov-action@v1
23.8 知识图谱
23.9 学习总结
核心要点:
- 严格遵守PEP8规范
- 全面覆盖单元测试
- 完善的文档体系
- 合理的项目结构
持续更新Python编程学习日志与技巧,敬请关注!
#编程# #学习# #python# #在头条记录我的2025#
猜你喜欢
- 2025-07-08 第十四章:Python并发编程(python并发原理)
- 2025-07-08 Python必会的20核心函数—range()函数
- 2025-07-08 第三章:Python控制结构(python控制结构有几种)
- 2025-07-08 第十一章:Python进阶话题(python 进阶)
- 2025-07-08 一文明白Python 的import如何工作
- 2025-07-08 python中的__init_.py,到底是什么?
- 2025-07-08 Python编程第7课,赋值语句高阶练习,4种方法交换两个变量的值
- 277℃Python短文,Python中的嵌套条件语句(六)
- 276℃python笔记:for循环嵌套。end=""的作用,图形打印
- 273℃PythonNet:实现Python与.Net代码相互调用!
- 268℃Python实现字符串小写转大写并写入文件
- 267℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 126℃原来2025是完美的平方年,一起探索六种平方的算吧
- 110℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 107℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)