当前位置:首页>python>Day 6 — Python 进阶语法

Day 6 — Python 进阶语法

  • 2026-09-02 16:41:53
Day 6 — Python 进阶语法

Week 2 · Python · 2小时


🎯 今日学习目标

  • 掌握面向对象编程,为 PyTorch nn.Module 打基础
  • 理解装饰器和上下文管理器
  • 学会使用 dataclass 和类型注解

📖 1. 面向对象编程

1.1 类与对象

PyTorch 的所有模型都继承自 nn.Module,理解 OOP 是使用框架的前提:

class LinearLayer:    def __init__(self, in_features, out_features):# 初始化权重 (正态分布)        self.weight = np.random.randn(out_features, in_features) * 0.01        self.bias = np.zeros(out_features)    def forward(self, x):        return x @ self.weight.T + self.bias    def __call__(self, x):        return self.forward(x)# 使用layer = LinearLayer(4, 2)x = np.random.randn(3, 4)# 3个样本,每个4维output = layer(x)# 通过 __call__ 自动调用 forwardprint(output.shape)# (3, 2)

1.2 继承与多态

PyTorch 中自定义模型继承 nn.Module,重写 forward 方法。这种设计让我们可以像搭积木一样组合模型。


📖 2. 装饰器与上下文管理器

2.1 装饰器

装饰器用于在不修改函数的前提下添加功能,在框架中大量使用:

import timefrom functools import wraps# 计时装饰器:测量函数执行时间def timer(func):    @wraps(func)    def wrapper(*args, **kwargs):        start = time.time()        result = func(*args, **kwargs)        elapsed = time.time() - start        print(f”{func.__name__} 耗时: {elapsed:.3f}s”)        return result    return wrapper@timerdef train_epoch(model, data):# 模拟训练    time.sleep(0.5)    return ”done”train_epoch(None, None)# train_epoch 耗时: 0.500s

2.2 上下文管理器

PyTorch 中 with torch.no_grad(): 就是上下文管理器,用于管理资源生命周期:

class Timer:    def __enter__(self):        self.start = time.time()        return self    def __exit__(self, *args):        print(f”耗时: {time.time() - self.start:.3f}s”)with Timer():# 这里的代码会被自动计时    sum(range(1000000))

📖 3. 类型注解与 dataclass

from dataclasses import dataclassfrom typing import List, Optionalimport numpy as np@dataclassclass TrainingConfig:    lr: float = 0.001    batch_size: int = 32    epochs: int = 100    device: str = ”cuda”    layers: List[int] = None    def __post_init__(self):        if self.layers is None:            self.layers = [128, 64]config = TrainingConfig(lr=0.01, epochs=50)print(config)# 自动生成 __repr__print(config.batch_size)# 32 (使用默认值)

✏️ 动手练习

  1. 实现一个 ReLU 激活函数类,继承上面的 LinearLayer 模式
  2. 写一个装饰器 @log_calls,记录函数调用次数和参数
  3. 用 dataclass 定义一个 ModelConfig,包含模型名、隐藏层维度列表、dropout 概率
  4. 实现一个上下文管理器 RandomSeed,在 with 块内设置随机种子,退出后恢复

✅ 今日总结

  • ✓ OOP 是理解 PyTorch 模型定义的前提
  • ✓ 装饰器在不修改函数的前提下添加功能
  • ✓ 上下文管理器管理资源(如 torch.no_grad())
  • ✓ dataclass 简化配置类的定义

📚 延伸阅读

  • Python 官方教程:https://docs.python.org/3/tutorial/classes.html
  • Real Python - Decorators:https://realpython.com/primer-on-python-decorators/
  • Fluent Python(Luciano Ramalho):Python 进阶必读

最新文章

随机文章