理解了Python函数,再理解Python装饰器就容易得多了。废话少说,先看下面的代码:
- # 装饰器函数,参数是另一个函数(被装饰的函数)
- def my_shiny_new_decorator(a_function_to_decorate):
- # 装饰器的内嵌函数,用来包装被修饰的函数
- def the_wrapper_around_the_original_function():
- # 在调用被修饰函数之前输出一行文本
- print("Before the function runs")
- # 调用被装饰函数
- a_function_to_decorate()
- # 在调用被修饰函数之后输出一行文本
- print("After the function runs")
- # 返回包装函数
- return the_wrapper_around_the_original_function
- # 这个函数将被my_shiny_new_decorator函数修饰
- def a_stand_alone_function():
- print("I am a stand alone function, don't you dare modify me")
- # 调用函数
- a_stand_alone_function()
- # 修饰a_stand_alone_function函数
- a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
- a_stand_alone_function_decorated()
执行这段代码,会输出如下内容:
- I am a stand alone function, don't you dare modify me
- Before the function runs
- I am a stand alone function, don't you dare modify me
- After the function runs
在这段代码中,通过my_shiny_new_decorator函数修饰了a_stand_alone_function函数,并在调用a_stand_alone_function函数前后各输出了一行文本。其实这就是Python装饰器的作用:包装函数。只是这里并没有使用装饰器的语法,而是用了最朴素的方式直接调用了装饰器函数来修饰a_stand_alone_function函数。