装饰器(Decorator)核心是高阶函数(函数可以接收函数作为参数,并返回一个新函数,包裹了原逻辑 + 新功能)。
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"调用 {func.__name__}()")
return func(*args, **kwargs)
return wrapper
@log_decorator
def greet():
print("Hello!")
语法糖 @log_decorator
这行相当于:greet = log_decorator(greet)
扩展:带参数的装饰器
装饰器本身也能接收参数(会多包一层函数,用于传递其它的参数):
def repeat(num_times):
def decorator_repeat(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
func(*args, **kwargs)
return wrapper
return decorator_repeat
@repeat(num_times=3)
def greet():
print("Hello!")
# @repeat(num_times=3) 装饰器参数
# 等价于
# decorator = repeat(num_timies=3) 先调用并返回结果(传递了参数)
# @decorator 然后再装饰
本文链接: Python小结
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
发布日期: 2025-08-01
最新构建: 2025-08-11
欢迎任何与文章内容相关并保持尊重的评论😊 !