Python装饰器通过封装函数增强功能,实现日志记录、权限校验、性能监控等横切关注点的分离。
Python装饰器本质上就是一个函数,它能接收一个函数作为参数,并返回一个新的函数。这个新函数通常在不修改原有函数代码的基础上,为其添加额外的功能或行为。它让我们的代码更模块化、可复用,并且更“优雅”地实现功能的增强或修改。它在很多场景下都能提升代码的可读性和可维护性,比如日志记录、性能监控、权限校验、缓存等。
解决方案
Okay, 咱们来聊聊Python装饰器这玩意儿。初次接触,很多人可能会觉得它有点“魔法”,但其实剥开来看,它就是函数式编程里一个很实用的概念。
简单来说,装饰器就是用来“包裹”另一个函数的。想象一下,你有一个函数,它能完成某个核心任务。但现在,你想在它执行前或执行后,或者在它执行过程中,加点额外的逻辑,比如记录日志、检查权限、计算执行时间等等。如果直接修改原函数,可能会让它变得臃肿,也破坏了它的单一职责。这时候,装饰器就派上用场了。
它的核心思想是:函数作为对象和闭包。
函数作为对象: 在Python里,函数和字符串、数字一样,都是一等公民。你可以把它赋值给变量,可以作为参数传给另一个函数,也可以作为另一个函数的返回值。这是理解装饰器的基石。
def greet(name): return f"Hello, {name}!" my_func = greet # 将函数赋值给变量 print(my_func("Alice")) # Hello, Alice!
闭包: 闭包是指一个函数定义在一个内部函数中,并且内部函数引用了外部函数作用域中的变量,即使外部函数已经执行完毕,内部函数仍然可以访问和操作这些变量。
def outer_function(msg): def inner_function(): print(msg) return inner_function closure_instance = outer_function("Hello from closure!") closure_instance() # Hello from closure!
把这两个概念结合起来,装饰器的基本形态就出来了:
def simple_decorator(func): def wrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper @simple_decorator def say_hello(): print("Hello!") @simple_decorator def add(a, b): print(f"Adding {a} and {b}") return a + b say_hello() # Output: # Something is happening before the function is called. # Hello! # Something is happening after the function is called. print(add(3, 5)) # Output: # Something is happening before the function is called. # Adding 3 and 5 # Something is happening after the function is called. # 8
这里的
@simple_decorator
say_hello = simple_decorator(say_hello)
say_hello
simple_decorator
simple_decorator
wrapper
say_hello
需要注意的是,
wrapper
*args
**kwargs
一个常见的坑是,装饰器会改变被装饰函数的元信息(比如
__name__
__doc__
functools.wraps
import functools def another_decorator(func): @functools.wraps(func) # 这一行很关键 def wrapper(*args, **kwargs): print(f"Calling function: {func.__name__}") return func(*args, **kwargs) return wrapper @another_decorator def my_function_with_docstring(x, y): """This is a test function.""" return x * y print(my_function_with_docstring.__name__) # my_function_with_docstring (如果没有 @functools.wraps 会是 wrapper) print(my_function_with_docstring.__doc__) # This is a test function.
Python装饰器在实际开发中究竟能解决哪些痛点?
在实际开发中,装饰器简直是代码组织和功能增强的利器。我个人觉得,它最核心的价值在于关注点分离。很多时候,我们会有一些横切关注点(cross-cutting concerns),比如日志记录、性能监控、权限校验、缓存等,这些功能会分散在程序的各个角落。如果每次都手动添加,代码会变得重复且难以维护。装饰器就提供了一种优雅的方式来处理这些。
举几个例子:
-
日志记录 (Logging): 这是最常见的场景之一。你想知道某个函数何时被调用,传入了什么参数,返回了什么结果。与其在每个函数内部都写一堆
或print
,不如用一个装饰器搞定。logging.info
import logging import functools logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def log_calls(func): @functools.wraps(func) def wrapper(*args, **kwargs): args_repr = [repr(a) for a in args] kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] signature = ", ".join(args_repr + kwargs_repr) logging.info(f"Calling {func.__name__}({signature})") result = func(*args, **kwargs) logging.info(f"{func.__name__} returned {result!r}") return result return wrapper @log_calls def divide(a, b): return a / b divide(10, 2) # 假设这里会抛出ZeroDivisionError,但日志依然会记录调用信息 # divide(10, b=0)
你看,
函数本身只关心除法逻辑,日志记录的“脏活累活”都交给装饰器了。divide
-
权限校验 (Authentication/Authorization): 在Web框架中尤其常见。某个视图函数只能让登录用户访问,或者只有管理员才能执行某个操作。
import functools def requires_login(func): @functools.wraps(func) def wrapper(*args, **kwargs): # 假设这里有一个检查用户是否登录的逻辑 is_logged_in = False # 模拟未登录 # is_logged_in = True # 模拟已登录 if not is_logged_in: print("Error: You must be logged in to access this page.") # 在Web框架中,这里可能会重定向到登录页或返回401错误 return None return func(*args, **kwargs) return wrapper @requires_login def view_secret_page(user_id): print(f"User {user_id} is viewing the secret page.") return "Secret content!" view_secret_page(123) # 未登录,会打印错误信息
这比在每个需要权限的函数开头都写一遍
要干净得多。if not current_user.is_authenticated(): ...
如何利用装饰器实现性能监控和
以上就是Python中装饰器基础入门教程 Python中装饰器使用场景的详细内容,更多请关注资源网其它相关文章!
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。