码迷,mamicode.com
首页 > 编程语言 > 详细

python3 装饰器

时间:2016-03-27 14:08:33      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 def outer(fun): # f 为用out装饰的函数
 2     def inner():
 3         print(装饰器!)
 4         fun()
 5         print(test)
 6     return inner
 7 
 8 @outer
 9 def fun1():
10     print(fun1)
11 
12 fun1()
code

运行的流程:outer(fun)---> @outer--->outer(fun)--->inner()--->return inner
--->fun1()--->outer(fun)--->inner()--->print(‘装饰器!‘)--->fun1():--->fun()
(打印出fun1)--->print(‘test‘)

 

主要用途是当有多个函数需要同时改动时,写一个修饰器函数,然后对每个函数进行修饰(@outer),而不用到第个函数内部进行重复的写这个函数,同时当新的功能需要添加进这个函数时,如:前面print(‘装饰器!‘),后面print(‘test‘),也直接添加即可,同时,装饰器函数也可以有返回值。

python3 装饰器

标签:

原文地址:http://www.cnblogs.com/Andy963/p/5325446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!