Python学习之路:装饰器实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import  time
 
def timer(func):#timer(test1) func=test1
    def deco():
        start_time=time.time()
        func()#run test1
        stop_time=time.time()
        print('the func run time is %s'%(stop_time-start_time))
    return deco
 
def test1():
    time.sleep(3)
    print('in the test1')
 
def test2():
    time.sleep(3)
    print('in the test2')
 
print(timer(test1))
test1=timer(test1)
test1()#----->deco
 
 
#-------------------------------------------------------------------
import  time
 
def timer(func):#timer(test1) func=test1
    def deco():
        start_time=time.time()
        func()#run test1
        stop_time=time.time()
        print('the func run time is %s'%(stop_time-start_time))
    return deco
 
@timer #加装饰器 test1=timer(test1)
def test1():
    time.sleep(3)
    print('in the test1')
 
@timer #加装饰器
def test2():
    time.sleep(3)
    print('in the test2')
 
test1()
test2()

 

posted @   Py小白  阅读(152)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示