Python装饰器的原理比想象中还要简单

理解了Python函数,再理解Python装饰器就容易得多了。废话少说,先看下面的代码:


  1. # 装饰器函数,参数是另一个函数(被装饰的函数) 
  2. def my_shiny_new_decorator(a_function_to_decorate): 
  3.     # 装饰器的内嵌函数,用来包装被修饰的函数 
  4.     def the_wrapper_around_the_original_function(): 
  5.         # 在调用被修饰函数之前输出一行文本 
  6.         print("Before the function runs"
  7.  
  8.         # 调用被装饰函数 
  9.         a_function_to_decorate() 
  10.  
  11.         # 在调用被修饰函数之后输出一行文本 
  12.         print("After the function runs"
  13.  
  14.     # 返回包装函数 
  15.     return the_wrapper_around_the_original_function 
  16.  
  17. # 这个函数将被my_shiny_new_decorator函数修饰 
  18. def a_stand_alone_function(): 
  19.     print("I am a stand alone function, don't you dare modify me"
  20.  
  21. # 调用函数 
  22. a_stand_alone_function() 
  23.  
  24. # 修饰a_stand_alone_function函数 
  25. a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function) 
  26. a_stand_alone_function_decorated() 

执行这段代码,会输出如下内容:


  1. I am a stand alone function, don't you dare modify me 
  2. Before the function runs 
  3. I am a stand alone function, don't you dare modify me 
  4. After the function runs 

在这段代码中,通过my_shiny_new_decorator函数修饰了a_stand_alone_function函数,并在调用a_stand_alone_function函数前后各输出了一行文本。其实这就是Python装饰器的作用:包装函数。只是这里并没有使用装饰器的语法,而是用了最朴素的方式直接调用了装饰器函数来修饰a_stand_alone_function函数。

【声明】:芜湖站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章