装饰器的作用
装饰器是Python的高级特性,可以在不修改函数代码的情况下增强功能。很多Python框架都使用装饰器实现核心功能。
defdecorator(func):
defwrapper(*args, **kwargs):
print("调用前")
result = func(*args, **kwargs)
print("调用后")
return result
return wrapper
@decorator
defhello():
print("Hello World!")
装饰器基本语法
掌握装饰器的核心语法。
defsimple_decorator(func):
definner():
print("装饰器开始")
func()
print("装饰器结束")
return inner
@simple_decorator
defgreet():
print("你好!")
greet()
带参数的装饰器
让装饰器更加灵活。
defrepeat(times):
defdecorator(func):
defwrapper(*args, **kwargs):
results = []
for _ in range(times):
results.append(func(*args, **kwargs))
return results
return wrapper
return decorator
@repeat(times=3)
defsay_hello():
return"Hello"
print(say_hello())
保留函数元信息
使用functools.wraps保持原函数信息。
from functools import wraps
defmy_decorator(func):
@wraps(func)
defwrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator
defexample():
"""这是一个示例函数"""
pass
print(example.__name__) # example
print(example.__doc__) # 这是一个示例函数
类装饰器实战
用类实现装饰器。
classCountCalls:
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
deffibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
装饰器链
多个装饰器可以叠加使用。
defuppercase(func):
defwrapper():
return func().upper()
return wrapper
defexclaim(func):
defwrapper():
return func() + "!"
return wrapper
@uppercase
@exclaim
defgreet():
return"hello"
print(greet()) # HELLO!
实战案例:性能计时器
用装饰器实现函数执行时间统计。
import time
from functools import wraps
deftimer(func):
@wraps(func)
defwrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 耗时: {end - start:.4f}秒")
return result
return wrapper
@timer
defslow_function():
time.sleep(2)
return"完成"
slow_function()
实战案例:权限验证
用装饰器实现访问控制。
defrequire_permission(permission):
defdecorator(func):
@wraps(func)
defwrapper(user, *args, **kwargs):
if permission notin user.get('permissions', []):
raise PermissionError(f"需要权限: {permission}")
return func(user, *args, **kwargs)
return wrapper
return decorator
@require_permission('admin')
defdelete_user(user, user_id):
print(f"用户 {user['name']} 删除了用户 {user_id}")
装饰器应用场景
装饰器的常见使用场景。
# 日志记录
deflog(func):
defwrapper(*args, **kwargs):
print(f"调用 {func.__name__}({args}, {kwargs})")
return func(*args, **kwargs)
return wrapper
# 缓存结果
defmemoize(func):
cache = {}
defwrapper(*args):
if args notin cache:
cache[args] = func(*args)
return cache[args]
return wrapper