Python中装饰器的使用

分类四类:

一、 函数式(不带参)
def decorator(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result
    return wrapper

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

greet("小乖")
  1. @decorator → 调用 decorator(func),返回 wrapper 函数。
  2. 调用 greet(“小乖”) → 实际执行 wrapper(“小乖”)。

原理:等价于func = Decorator(func)。

二、函数式(带参)
def decorator(level):
    def callable(func):
        def wrapper(*args, **kwargs):
            print(f"装饰器参数: level={level}")
            result = func(*args, **kwargs)
            return result
        return wrapper
    return callable

@decorator(level="INFO")
def greet(name):
    print(f"Hello, {name}!")

greet("小白")
  1. @decorator(level=“INFO”) → 调用 decorator(“INFO”),返回 callable 函数。
  2. Python 发现 callable 是一个可调用对象,于是调用 callable(func),返回 wrapper 函数。
  3. 调用 greet(“小白”) → 实际执行 wrapper(“小白”)。

原理:等价于decorator = Decorator('参数'),然后func = decorator(func)。

三、 类式(不带参)
class Decorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        result = self.func(*args, **kwargs)
        return result

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

greet("小乖")
  1. @Decorator → 调用 Decorator.init(greet),绑定函数 greet,返回实例DecoratorInstance替换掉greet。
  2. 调用 greet(“小乖”),实际上是调用DecoratorInstance → 触发 Decorator.call(“小乖”),执行装饰逻辑后调用原函数。
四、 类式(带参)
class Decorator:
    def __init__(self, level):
        self.level = level

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            return result
        return wrapper

@Decorator(level="INFO")
def greet(name):
    print(f"Hello, {name}!")

greet("小白")
  1. @Decorator(level=“INFO”) → 调用 Decorator.init(“INFO”),存储参数 level,返回实例DecoratorInstance。
  2. Python 发现 DecoratorInstance 是可调用的(有 call 方法),于是调用 call(func),返回 wrapper 函数。
  3. 调用 greet(“小白”) → 实际执行 wrapper(“小白”)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值