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

Python3 之装饰器

时间:2017-10-04 11:51:28      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:cti   修改   调用   time()   time   span   strong   else   sleep   

装饰器的作用:扩展函数功能。

特点:1.不修改原函数代码

           2.保持调用函数不变

 

原理:高阶函数 + 嵌套函数 = 装饰器

 

 1 # Author = Johnston
 2 import time
 3 def timer(func):
 4     def deco():
 5         start_time = time.time()
 6         func()
 7         end_time = time.time()
 8         print("the function run time is %s" %(end_time-start_time))
 9     return deco
10 
11 @timer  #bar = timer(bar),@time必须写在需装饰的函数前面
12 def bar():
13     time.sleep(3)
14     print("in the bar")
15 
16 bar()

无参数装饰器

 


# Author = Johnston
import time
def timer(func):
    def deco(name):                       #传递参数name
        start_time = time.time()
        func(name)
        end_time = time.time()
        print("the function run time is %s" %(end_time-start_time))
    return deco

@timer  #bar = timer(bar),@timer必须写在需装饰的函数前面
def bar(name):
    time.sleep(3)
    print("%s is in the bar" %name)

bar("Johnston")

 内参装饰器 

 


 1 # Author = Johnston
 2 import time
 3 def outpara(type):
 4     def timer(func):
 5         def deco(name):
 6             if type==1:          #根据外参数作为判断执行条件
 7                 start_time = time.time()
 8                 func(name)
 9                 end_time = time.time()
10                 print("the function run time is %s" %(end_time-start_time))
11             else:
12                 print("wrong type")
13         return deco
14     return timer
15 
16 @outpara(type=1)  #传递条件参数,@outpara必须写在需装饰的函数前面
17 def bar(name):
18   time.sleep(3)
19   print("%s is in the bar" %name)
20
21 bar("Johnston")
外参装饰器 

 

Python3 之装饰器

标签:cti   修改   调用   time()   time   span   strong   else   sleep   

原文地址:http://www.cnblogs.com/automate/p/7624928.html

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