工作原理基于 Python 的两个关键机制:
类的实例化过程(init)
实例的可调用性(call)
class Decorator:
def __init__(self, func): # 接收被装饰函数
self.func = func
def __call__(self, *args, **kwargs): # 替代 wrapped
print("Before call")
result = self.func(*args, **kwargs)
print("After call")
return result
@Decorator
def say_hello():
print("Hello!")
@Decorator 触发 Decorator(say_hello) → 调用 init
创建实例并保存原函数 self.func = say_hello
调用 say_hello() 时实际调用实例的 call 方法