Python 装饰器的作用与还原示例

1. 装饰器的作用
装饰器(Decorator)是 Python 中的一种高级功能,用于动态修改函数或类的行为,而无需修改其原始代码。它的核心作用包括:

  • 代码复用:将通用逻辑(如日志记录、权限检查)封装到装饰器中,避免重复代码。
  • 功能扩展:在不修改原函数的情况下,增加额外功能。
  • 解耦:将核心逻辑与辅助逻辑分离,提高代码可读性和可维护性。

2. 装饰器的基本语法
装饰器本质上是一个高阶函数,它接收一个函数作为参数,并返回一个新的函数。

示例:记录函数执行时间的装饰器

import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)  # 调用原函数
        end_time = time.time()
        print(f"{func.__name__} 执行时间: {end_time - start_time:.4f} 秒")
        return result
    return wrapper

@timer_decorator
def my_function():
    time.sleep(2)
    print("函数执行完成")

my_function()

输出:

函数执行完成
my_function 执行时间: 2.0021

3. 装饰器的还原
装饰器的语法糖 @decorator 实际上是一种简写形式。我们可以将其还原为普通的函数调用。

3.1 还原步骤

  • 定义装饰器函数(如 timer_decorator)。
  • 将目标函数(如 my_function)作为参数传递给装饰器。
  • 使用装饰器返回的新函数替换原函数。

3.2 还原示例
将以下装饰器写法还原为普通函数调用:

@timer_decorator
def my_function():
    time.sleep(2)
    print("函数执行完成")

还原后的代码:

def my_function():
    time.sleep(2)
    print("函数执行完成")

# 手动应用装饰器
my_function = timer_decorator(my_function)

# 调用函数
my_function()

输出:

函数执行完成
my_function 执行时间: 2.0021

4. 多层装饰器的还原
如果一个函数被多个装饰器修饰,它们的应用顺序是从下到上(从内到外)。

示例:多层装饰器

def decorator1(func):
    def wrapper():
        print("Decorator 1 开始")
        func()
        print("Decorator 1 结束")
    return wrapper

def decorator2(func):
    def wrapper():
        print("Decorator 2 开始")
        func()
        print("Decorator 2 结束")
    return wrapper

@decorator1
@decorator2
def my_function():
    print("函数执行")

my_function()

输出:

Decorator 1 开始
Decorator 2 开始
函数执行
Decorator 2 结束
Decorator 1 结束

还原后的代码

def my_function():
    print("函数执行")

# 从下到上应用装饰器
my_function = decorator2(my_function)
my_function = decorator1(my_function)

# 调用函数
my_function()

5. 带参数的装饰器
如果装饰器本身需要参数,则需要再嵌套一层函数。

示例:带参数的装饰器

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

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

greet("Alice")

输出:

Hello, Alice!
Hello, Alice!
Hello, Alice!

还原后的代码

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

# 手动应用装饰器
greet = repeat(3)(greet)

# 调用函数
greet("Alice")

6. 总结
装饰器的作用:动态扩展函数功能,实现代码复用和解耦。

装饰器的本质:高阶函数,接收函数并返回新函数。

还原装饰器:将 @decorator 语法糖还原为普通函数调用,便于理解其工作原理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦幻南瓜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值