分类四类:
一、 函数式(不带参)
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result
return wrapper
@decorator
def greet(name):
print(f"Hello, {name}!")
greet("小乖")
- @decorator → 调用 decorator(func),返回 wrapper 函数。
- 调用 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("小白")
- @decorator(level=“INFO”) → 调用 decorator(“INFO”),返回 callable 函数。
- Python 发现 callable 是一个可调用对象,于是调用 callable(func),返回 wrapper 函数。
- 调用 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("小乖")
- @Decorator → 调用 Decorator.init(greet),绑定函数 greet,返回实例DecoratorInstance替换掉greet。
- 调用 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("小白")
- @Decorator(level=“INFO”) → 调用 Decorator.init(“INFO”),存储参数 level,返回实例DecoratorInstance。
- Python 发现 DecoratorInstance 是可调用的(有 call 方法),于是调用 call(func),返回 wrapper 函数。
- 调用 greet(“小白”) → 实际执行 wrapper(“小白”)