python 视频教程请点击我领取学习

1. 函数装饰器(装饰函数)

def simple_decorator(func):
    def wrapper():
        print("函数执行前")
        func()
        print("函数执行后")
    return wrapper

@simple_decorator
def say_hello():
    print("Hello!")

# 使用
say_hello()
# 输出:
# 函数执行前
# Hello!
# 函数执行后

2. 类装饰器(装饰函数)

class ClassDecorator:
    def __init__(self, func):
        self.func = func
    
    def __call__(self, *args, **kwargs):
        print("类装饰器 - 执行前")
        result = self.func(*args, **kwargs)
        print("类装饰器 - 执行后")
        return result

@ClassDecorator
def say_hi():
    print("Hi!")

# 使用
say_hi()
# 输出:
# 类装饰器 - 执行前
# Hi!
# 类装饰器 - 执行后

3. 带参数的装饰器

def repeat(times):
    """带参数的装饰器"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            for i in range(times):
                print(f"第 {i+1} 次执行:")
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(times=3)
def greet(name):
    print(f"你好, {name}!")

# 使用
greet("小明")
# 输出:
# 第 1 次执行:
# 你好, 小明!
# 第 2 次执行:
# 你好, 小明!
# 第 3 次执行:
# 你好, 小明!

4、更复杂的带参数类装饰器

class ParamClassDecorator:
    def __init__(self, prefix="结果:"):
        self.prefix = prefix
    
    def __call__(self, func):
        def wrapper(*args, **kwargs):
            print(f"{self.prefix} 开始执行函数")
            result = func(*args, **kwargs)
            print(f"{self.prefix} 函数执行完毕")
            return result
        return wrapper

@ParamClassDecorator(prefix="✨装饰器日志✨")
def calculate(a, b):
    return a + b

# 使用
result = calculate(5, 3)
print(f"计算结果: {result}")
# 输出:
# ✨装饰器日志✨ 开始执行函数
# ✨装饰器日志✨ 函数执行完毕
# 计算结果: 8

5、实际应用示例:计时装饰器

import time

def timer(unit='s'):
    """计时装饰器,可选择时间单位"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            end = time.time()
            
            duration = end - start
            if unit == 'ms':
                duration *= 1000
                print(f"{func.__name__} 执行时间: {duration:.2f} 毫秒")
            else:
                print(f"{func.__name__} 执行时间: {duration:.2f} 秒")
            
            return result
        return wrapper
    return decorator

@timer(unit='ms')
def slow_function():
    time.sleep(0.1)
    return "完成"

# 使用
result = slow_function()
print(result)

总结

  • 函数装饰器:最简单的装饰器形式,接收函数作为参数

  • 类装饰器:通过类的 __call__ 方法实现,可以维护状态

  • 带参数装饰器:需要三层嵌套,最外层接收装饰器参数,中间层接收函数,最内层是实际包装函数

装饰器是Python中强大的元编程工具,可以优雅地扩展函数功能而不修改原函数代码。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐