欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

Python 装饰器从入门到进阶

时间:2026年08月12日 04:46:50 浏览:0

基础装饰器


装饰器本质上是一个函数,接收函数作为参数,返回增强后的函数。


def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} 耗时 {time.time() - start:.2f}s")
return result
return wrapper

@timer
def slow_function():
import time
time.sleep(1)
return "done"

slow_function()

带参数的装饰器


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

@repeat(3)
def say_hello():
print("Hello")

类装饰器


class CountCalls:
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
print(f"调用次数: {self.count}")
return self.func(*args, **kwargs)

@CountCalls
def test():
pass

保留元信息


from functools import wraps

def decorator(func):
@wraps(func) # 保留 __name__ 和 __doc__
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper

装饰器是 Python 优雅设计的典范,广泛应用于日志、权限、缓存等场景。