(摸鱼烤肉)5个能让代码减半的Python装饰器

news/2025/4/25 7:58:05/

什么是装饰器

包装器,英文wrapper,一种函数,能够作用于别的函数从而给被作用的函数添加新功能,或是修改其行为。包装器通常以装饰器(英文是decorator)的形式实现,装饰器将另一个函数作为输入,并对功能做一些改进。

包装器可以被应用于很多场景:

  • 功能扩展:添加一些特征(features),比如打印日志(logging),评估性能或者缓存。
  • 代码复用:包装器无疑可以被应用到很多地方,既能防止代码重复,又能确保跨组件的一致行为。
  • 行为修改:我们可以解释输入参数,比如,在不需要写很多assert语句的前提下避免许多输入变量。

例子🍒来了

下面的例子会说服你相信装饰器是日常工作中不可或缺的。

1 - Timer

timer能够用来计算和打印一个函数的执行时间。

import timedef timer(func):def wrapper(*args, **kwargs):# start the timerstart_time = time.time()# call the decorated functionresult = func(*args, **kwargs)# remeasure the timeend_time = time.time()# compute the elapsed time and print itexecution_time = end_time - start_timeprint(f"Execution time: {execution_time} seconds")# return the result of the decorated function executionreturn result# return reference to the wrapper functionreturn wrapper

定义了一个名为timer的函数,timer接收func为参数,证明其是一个装饰器函数。在timer的内部,定一个名为wrapper的函数,想要传给被装饰函数的参数由wrapper来接收。

在wrapper内部,用提供的参数调用被装饰函数,即

result = func(*args, **kwargs)

最终,wrapper返回了被装饰函数的执行。装饰器函数(timer)应当返回wrapper的索引。

我们选一个被装饰函数来用一下装饰器

@timer
def train_model():print("Starting the model training function...")# simulate a function execution by pausing the program for 5 secondstime.sleep(5) print("Model training completed!")train_model() 

输出为

Starting the model training function...
Model training completed!
Execution time: 5.0018792152404785 seconds

2 - Debugger

未完待续

3 - Retry

如果你的函数涉及到网络的处理或API的调用,那么装饰器retry将非常有用。retry可以让一个函数重复执行固定的次数,同时能设置次数之间的延迟。

import timedef retry(max_attempts, delay=1):def decorator(func):def wrapper(*args, **kwargs):attempts = 0while attempts < max_attempts:try:return func(*args, **kwargs)except Exception as e:attempts += 1print(f"Attempt {attempts} failed: {e}")time.sleep(delay)print(f"Function failed after {max_attempts} attempts")return wrapperreturn decorator

 用法

@retry(max_attempts=3, delay=2)
def fetch_data(url):print("Fetching the data..")# raise timeout error to simulate a server not responding..raise TimeoutError("Server is not responding.")
fetch_data("https://example.com/data")  # Retries 3 times with a 2-second delay between attempts

输出

Fetching the data..
Attempt 1 failed: Server is not responding.
Fetching the data..
Attempt 2 failed: Server is not responding.
Fetching the data..
Attempt 3 failed: Server is not responding.
Function failed after 3 attempts 

原文链接

Five Python Decorators That Can Reduce Your Code By Half


http://www.ppmy.cn/news/1049908.html

相关文章

数据结构(1)

数据结构其实就是将数据按照一定的关系组织起来的集合&#xff0c;用于组织和存储数据。 1.数据结构分类 1.逻辑结构 逻辑结构是从具体问题中抽象出来的模型&#xff0c;是抽象意义的结构&#xff0c;按照对象中数据的相互关系进行分类。 1>集合结构&#xff1a;集合结构中…

SpringBootWeb案例 Part 2

3. 员工管理 完成了部门管理的功能开发之后&#xff0c;我们进入到下一环节员工管理功能的开发。 基于以上原型&#xff0c;我们可以把员工管理功能分为&#xff1a; 分页查询 带条件的分页查询 删除员工 新增员工 修改员工 那下面我们就先从分页查询功能开始学习。 3.…

【Linux】cpolar+JuiceSSH实现手机端远程连接Linux服务器

文章目录 1. Linux安装cpolar2. 创建公网SSH连接地址3. JuiceSSH公网远程连接4. 固定连接SSH公网地址5. SSH固定地址连接测试 处于内网的虚拟机如何被外网访问呢?如何手机就能访问虚拟机呢? cpolarJuiceSSH 实现手机端远程连接Linux虚拟机(内网穿透,手机端连接Linux虚拟机) …

cloud_mall-notes02

1、多条件分页查询page ApiOperation("多条件分页查询xxxx")GetMapping("page")PreAuthorize("hasAuthority(模块权限:权限:page)")public ResponseEntity<Page<实体类>> loadxxxxPage(Page<实体类> page,实体类 domain) {pag…

机器学习之数据清洗

一、介绍 数据清洗是机器学习中的一个重要步骤&#xff0c;它涉及对原始数据进行预处理和修复&#xff0c;以使数据适用于机器学习算法的训练和分析。数据清洗的目标是处理数据中的噪声、缺失值、异常值和不一致性等问题&#xff0c;以提高数据的质量和准确性。 二、方法 处理…

基于JJWT理解JWT,JWS,JWE

JWT &#xff0c; 全写JSON Web Token, 是开放的行业标准RFC7591&#xff0c;用来实现端到端安全验证. 从开发者理解的角度来说&#xff1a; JWT 是一个定义传递信息的标准JWT 的Token是一个Base64编码的字符串&#xff0c; 类似 eyJhbGciOiJIUzI1NyJ9.eyJzdWIiOiJvc2NhciJ9.…

Kubernetes(K8s)从入门到精通系列之十六:linux服务器安装minikube的详细步骤

Kubernetes K8s从入门到精通系列之十六:linux服务器安装minikube的详细步骤 一、安装Docker二、创建启动minikube用户三、下载minikube四、安装minikube五、将minikube命令添加到环境变量六、启动minikube七、查看pods,自动安装kubectl八、重命名minikube kubectl --为kubect…

vscode如何关闭受限模式

受限模式旨在实现安全地浏览代码 第一步&#xff1a; 第二步&#xff1a;输入trust,找到Security.workspace.trust,取消勾选 第三步&#xff1a; 重启vscode.