你如何理解 Python 中的装饰器?
装饰器是Python中一个强大的功能,它允许用户在不修改原有函数代码的情况下,增加函数的额外功能。装饰器通过在函数定义之前使用@
符号应用,实际上是一个接受函数作为参数并返回新函数的高阶函数。装饰器可以用于日志记录、性能测试、事务处理、缓存、权限校验等场景。
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
输出:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
在这个例子中,my_decorator
是一个装饰器,它包装了 say_hello
函数,并在调用 say_hello
之前和之后添加了一些额外的逻辑。
Spring Boot 中的类似概念
在 Spring Boot 中,装饰器的概念可以通过**AOP