day9-1 装饰器2

 1 import time
 2 
 3 def timeer(func):
 4     def warpper(*args,**kwargs):
 5         st_time = time.time()
 6         res = func(*args,**kwargs)
 7         sp_time = time.time()
 8         print("the func run time is %s" %(sp_time - st_time))
 9         return res
10     return warpper
11 
12 @timeer   # test1 = timeer(test1) = warpper
13 def test1():
14     "!!!!"
15     time.sleep(3)
16     print("in the test1")
17     return 'my LOVE'
18 @timeer
19 def test2(name):
20     time.sleep(2)
21     print("in the test2 name is:",name)
22 @timeer
23 def test3(**kwargs):
24     time.sleep(1)
25     print("in the test3:",kwargs)
26 
27 test1()  # test1 = warpper()
28 print(test1())
29 test2('qq')
30 test3(name='RI',age=18)
31 
32 # =============================================================================
33 # in the test1
34 # the func run time is 3.0011308193206787
35 # in the test1
36 # the func run time is 3.009918451309204
37 # my LOVE
38 # in the test2 name is: qq
39 # the func run time is 2.009945869445801
40 # in the test3: {'name': 'RI', 'age': 18}
41 # the func run time is 1.0099740028381348
42 # =============================================================================

装饰器由高阶函数和嵌套函数组成。

高阶函数的特点。

一,高阶函数把一个函数名当做实参传递给另一个函数(装饰器可以在不修改源代码的情况下为其添加功能)

二,返回一个函数名(因此在装饰器不会改变原函数的调用方式)

嵌套函数 

def test():

    test2()

这种方式是调用

def test():

    def test2():

        pass

函数嵌套

嵌套函数可以为原函数添加功能

装饰器的本质上函数,对装饰的函数是透明的,不会改变其调用方式,同时利用嵌套函数为其添加功能

猜你喜欢

转载自www.cnblogs.com/yfjly/p/9775810.html