首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ Python / 文章详情

Python 装饰器简单代码

Sonder
4天前
2566字
6分钟
浏览 (23)

复制代码
import time
from functools import wraps

# 模拟发送短信函数
def send_sms_auth(phone):
    print(f"发送短信到: {phone}")
    raise Exception("短信发送服务不可用")

# 装饰器
def time_it(max_retries=3):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print(f"=== 开始执行 {func.__name__} ===")
            for attempt in range(max_retries):
                try:
                    print(f"第 {attempt + 1} 次尝试")
                    result = func(*args, **kwargs)
                    print(f"=== {func.__name__} 执行成功 ===")
                    return result
                except Exception as e:
                    print(f"失败: {e}")
                    if attempt == max_retries - 1:
                        print(f"=== {func.__name__} 所有重试失败 ===")
                        raise e
                    time.sleep(1)
        return wrapper
    return decorator

# 重新定义函数,确保没有重复装饰
def complex_feature_engineering(data):
    print("正在进行复杂的特征工程...")
    resp = send_sms_auth("aaaa")
    print(f"=>complex_feature_engineering=>行数:58====> {resp}")
    return "特征工程完成"

def model_preprocessing(data):
    print("正在进行模型预处理...")
    for i in range(2):
        print(f"处理中... {i + 1}/2")
        time.sleep(1)
    return "预处理完成"

# 手动应用装饰器(避免重复)
complex_feature_engineering = time_it()(complex_feature_engineering)
model_preprocessing = time_it()(model_preprocessing)

# 主程序
if __name__ == "__main__":
    print("开始测试:")

    # 测试失败的情况
    try:
        result1 = complex_feature_engineering("数据")
        print(f"结果: {result1}")
    except Exception as e:
        print(f"最终失败: {e}")

    print("\n测试成功的情况:")
    result2 = model_preprocessing("数据")
    print(f"结果: {result2}")

日志:

复制代码
C:\Users\admin\miniconda3\envs\websoket_ui\python.exe C:\app\websoket_ui\case\debugging_code.py 
开始测试:
=== 开始执行 complex_feature_engineering ===
第 1 次尝试
正在进行复杂的特征工程...
发送短信到: aaaa
失败: 短信发送服务不可用
第 2 次尝试
正在进行复杂的特征工程...
发送短信到: aaaa
失败: 短信发送服务不可用
第 3 次尝试
正在进行复杂的特征工程...
发送短信到: aaaa
失败: 短信发送服务不可用
=== complex_feature_engineering 所有重试失败 ===
最终失败: 短信发送服务不可用

测试成功的情况:
=== 开始执行 model_preprocessing ===
第 1 次尝试
正在进行模型预处理...
处理中... 1/2
处理中... 2/2
=== model_preprocessing 执行成功 ===
结果: 预处理完成

进程已结束,退出代码为 0

超简易:

复制代码
def my_decorator(func):
   def wrapper():
       print("执行装饰器中的代码")
       func()
       print("再次执行装饰器中的代码")
   return wrapper

@my_decorator
def say_hello():
   print("你好,世界!")

say_hello()

这个回答让你豁然开朗,其实跟中间件差不多的意思
为什么python要有装饰器这个设计? - CodeCrafter的回答 - 知乎

下一篇 / 实现 Element-UI 官网的主题切换动画

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)