python第42天打卡
1. 回调函数 (Callback Functions)
概念:
回调函数是作为参数传递给另一个函数的函数,在特定事件或条件发生时被调用。常用于异步操作、事件处理等场景。
特点:
解耦代码逻辑
增强可扩展性
常见于 GUI 编程、深度学习训练回调
def process_data(data, callback):print("Processing data...")result = data * 2callback(result) # 在适当时候调用回调函数def save_result(res):print(f"Saving result: {res}")process_data(10, save_result)
2. Lambda 函数
概念:
匿名函数,用 lambda
关键字定义的一行简单函数,无需函数名。
特点:
简洁处理简单操作
常与高阶函数(如 map()
, filter()
, sorted()
)配合使用
# 平方计算
square = lambda x: x ** 2
print(square(5)) # 输出 25# 在 sorted 中使用
points = [(1, 2), (3, 1), (5, 4)]
sorted_points = sorted(points, key=lambda p: p[1]) # 按 y 坐标排序
print(sorted_points) # 输出 [(3, 1), (1, 2), (5, 4)]
3. Hook 函数(模块钩子与张量钩子)
概念:
Hook 是拦截神经网络中间层输入/输出的技术,用于:
可视化特征图
提取中间层激活值
修改梯度
def forward_hook(module, input, output):print(f"Layer: {module.__class__.__name__}")print(f"Output shape: {output.shape}")model.conv1.register_forward_hook(forward_hook)
@浙大疏锦行