HOME / NOTES / Python 装饰器深入理解
📝

> Python 装饰器深入理解

深入理解 Python 装饰器的工作原理、常见用法和高级技巧。

装饰器基础

装饰器是 Python 中一个强大的特性,本质上是一个高阶函数。

基本语法

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("函数执行前")
        result = func(*args, **kwargs)
        print("函数执行后")
        return result
    return wrapper

@my_decorator
def hello():
    print("Hello, World!")

带参数的装饰器

def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for i in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

实际应用场景

  • 性能测试和日志记录
  • 权限验证
  • 缓存机制
  • 重试机制