Python高级编程规范与高阶模式详解
Python 常见规范与高阶模式
以下文档汇总了 Python 中常用的命名规范、函数签名约定、装饰器、类型注解、魔法方法,以及在大型项目中常见的架构和操作模式。
1. 命名规范(Naming Conventions)
| 前缀/形式 | 含义 | 示例 |
|---|---|---|
age |
普通变量/属性 | age = 30 |
_age |
单下划线:弱“私有”标记,不建议外部使用 | self._age = 30 |
__age |
双下划线:名称改写(name mangling) | self.__age = 30 |
__age__ |
双前后下划线:系统保留(魔法方法/特殊属性) | __init__, __str__ |
ALL_CAPS |
常量 | MAX_RETRIES = 5 |
snake_case |
下划线式,函数/变量推荐 | compute_value() |
MixedCase |
类名,首字母大写驼峰式 | class MyClass: |
mixedCase |
驼峰式,不推荐,少见 | someVar |
module_name |
文件或包名,均使用小写+下划线 | utils/helpers.py |
额外补充:
__slots__:定义在类中,限制实例属性集合。__name__, __all__, __version__。2. 函数签名与参数约定
def func(pos1, pos2, /, arg1, arg2=42, *args, kw_only1, kw_only2=None, **kwargs) -> ReturnType:
...
/ 前参数只能通过位置传递(Python 3.8+)。*args:可变位置参数收集为元组。kw_only:在 * 后的参数必须通过关键字传递。**kwargs:可变关键字参数收集为字典。-> ReturnType:返回值类型注解。额外补充:
def f(*, a, b): 强制 a、b 为关键字。def f(a, b, /, c): 强制 a、b 为位置。typing 模块:List[int], Dict[str, Any], Optional[T]。3. 装饰器(Decorators)
@decorator:在函数/类定义时应用,等价于:
func = decorator(func)
内置常用装饰器:
@staticmethod@classmethod@property@functools.lru_cache自定义装饰器:接收被装饰对象并返回新对象。可用于权限校验、缓存、日志等场景。
额外补充:
def deco(arg): ... 返回实际装饰器。functools.wraps:保持原函数元数据。4. 类型注解(Type Hints)
from typing import List, Dict, Optional, Union, Any
def greet(name: str, times: int = 1) -> None:
...
def parse(data: bytes) -> Union[Dict[str, Any], None]:
...
list[int], dict[str, float]。# type: ignore 用于忽略特定行的类型检查。TypeVar, Generic 用于定义泛型类。5. 魔法方法与协议(Special Methods & Protocols)
常见魔法方法:
__init__, __new__, __repr__, __str____len__, __getitem__, __setitem__, __contains____call__, __iter__, __next____add__, __eq__, __lt__ 等__enter__, __exit__协议(Protocol):结构化子类型,只要实现签名即可视为该类型。
额外补充:
with 语句。__iter__ 与 __next__。6. 代码组织与项目结构
my_project/
├── src/ # 源码目录
│ └── my_package/
│ ├── __init__.py
│ ├── core.py
│ └── utils.py
├── tests/ # 单元测试
│ └── test_core.py
├── docs/ # 文档(Sphinx / MkDocs)
├── configs/ # 配置文件(yaml/json)
├── requirements.txt
├── pyproject.toml # Poetry / PEP 517
└── .github/workflows/ # CI 配置
额外补充:
api/, service/, repository/, models/。__all__ 控制 from module import *。7. 大型项目常用操作模式
- 日志记录(Logging):
logging.getLogger(__name__)+ 配置Handler。 - 配置管理:
pydantic,dataclasses, 环境变量加载。 - 测试:
pytest+ fixtures +mock。 - 静态检查:
mypy,flake8,isort,black。 - 依赖管理:
poetry,pipenv。 - CI/CD:GitHub Actions / GitLab CI。
- 文档生成:
Sphinx+autodoc/MkDocs。 - 数据库/ORM:
SQLAlchemy,Django ORM,asyncpg。 - 异步编程:
asyncio,aiohttp,FastAPI。 - 缓存:
redis,memcached。 - 任务队列:
Celery,RQ。 - 监控:
Prometheus,Sentry。 - 打包分发:
setuptools,twine。
如有更多场景(如元类、AST 操作、性能调优、C 扩展等)可继续补充。
作者:梦道长生