装饰器简介
装饰器是一种设计模式,用于在不改变原函数的情况下,动态地向函数添加功能。装饰器本质上是一个高阶函数,它接受一个函数作为参数,并返回一个新的函数。
装饰器的基本语法
装饰器的使用非常简单,只需在函数定义之前加上 @decorator_name 即可。
示例代码
def decorator(func):
def wrapper(*args, **kwargs):
print("Function is being called")
result = func(*args, **kwargs)
print("Function has been called")
return result
return wrapper
@decorator
def say_hello(name):
print(f"Hello, {name}")
say_hello("Alice")
在这个示例中:
decorator是装饰器函数。@decorator应用于say_hello函数,使得say_hello被调用时,会先执行decorator中的wrapper函数逻辑。
装饰器的应用场景
-
日志记录
记录函数调用的相关信息,便于调试和监控。
def log_decorator(func): def wrapper(*args, **kwargs): print(f"Calling function {func.__name__} with arguments {args} and {kwargs}") result = func(*args, **kwargs) print(f"Function {func.__name__} returned {result}") return result return wrapper @log_decorator def add(a, b): return a + b add(3, 5) -
权限验证
检查用户权限,控制函数访问。
def authorize(func): def wrapper(user, *args, **kwargs): if user == "admin": return func(*args, **kwargs) else: print("Permission denied") return wrapper @authorize def view_dashboard(): print("Dashboard is being viewed") view_dashboard("admin") view_dashboard("guest") -
缓存机制
对函数结果进行缓存,提高性能。
def cache(func): results = {} def wrapper(*args): if args in results: return results[args] result = func(*args) results[args] = result return result return wrapper @cache def fibonacci(n): if n in (0, 1): return n return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(10))
装饰器的嵌套使用
多个装饰器可以同时应用于一个函数,顺序从内到外执行。
示例代码
def decorator1(func):
def wrapper(*args, **kwargs):
print("Decorator 1 before")
result = func(*args, **kwargs)
print("Decorator 1 after")
return result
return wrapper
def decorator2(func):
def wrapper(*args, **kwargs):
print("Decorator 2 before")
result = func(*args, **kwargs)
print("Decorator 2 after")
return result
return wrapper
@decorator1
@decorator2
def greet(name):
print(f"Hello, {name}")
greet("Bob")
在这个示例中,decorator2 首先被应用,其次是 decorator1。
结论
装饰器是Python中的一个强大功能,简化了许多常见的编程任务,如日志记录、权限控制、性能优化等。它使得代码更具可读性和可维护性,鼓励模块化和复用性。理解和熟练使用装饰器,可以大大提高开发效率和代码质量。