标签:and rand 源代码 mil 获取 分隔符 sleep soft 变量
1、装饰器的定义
装饰器的本质就是函数,用来装饰其它函数,就是为其它函数添加附加功能。
装饰器原则如下:
2、实现装饰器知识储备
1 def bar(): 2 print("in the bar") 3 def foo(): 4 print("in the foo") 5 bar() 6 7 foo() 8 9 print("----------分割线-----------") 10 11 def foo1(): 12 print("in the foo") 13 bar1() 14 def bar1(): 15 print("in the bar") 16 17 foo1() 18 19 print("----------分割线-----------") 20 # 这样会报错 21 # def foo2(): 22 # print("in the foo") 23 # bar2() 24 # foo2() 25 # def bar2(): 26 # print("in the bar")
1 import time 2 3 def bar1(): 4 time.sleep(3) 5 print("in the bar") 6 7 def test2(func): 8 start_time = time.time() 9 func() # 相当于运行bar1() 10 stop_time = time.time() 11 print("total run time %s" %(stop_time - start_time)) 12 13 test2(bar1)
1 def bar2(): 2 time.sleep(3) 3 print("in the bar2") 4 5 def test3(func): 6 print(func) 7 return func 8 9 print(test3(bar2)) # 获取的是内存地址 10 11 res = test3(bar2) 12 res()
1 def foo(): 2 print("in the foo") 3 def bar(): 4 print("in the bar") 5 bar() # 局部变量只能在其作用域内调用 6 7 foo()
1 x = 0 2 def grandpa(): 3 x = 1 4 def dad(): 5 x = 2 6 def son(): 7 x = 3 8 print(x) # 最终打印结果为3 9 son() 10 dad() 11 grandpa()
1 import time 2 3 4 def timer(func): 5 def deco(): 6 start_time = time.time() 7 func() 8 stop_time = time.time() 9 print("total time is %s" % (stop_time - start_time)) 10 return deco # 返回deco()的内存地址 11 12 13 def test1(): 14 time.sleep(3) 15 print("in the test1") 16 17 18 def test2(): 19 time.sleep(3) 20 print("in the test2") 21 22 23 timer(test1) # test1的内存地址赋值给func,返回deco()的内存地址 24 print(timer(test1)) # 返回deco()的内存地址 25 test1 = timer(test1) # 内存地址赋值给test1 26 test1() # 相当于执行deco() 27 28 timer(test2) 29 test2 = timer(test2) 30 test2() 31 32 print("---------我是分隔符---------") 33 34 35 # 装饰器语法如下 36 @timer # 相当于test1 = timer(test1) 37 def test1(): 38 time.sleep(3) 39 print("in the test1") 40 41 42 @timer 43 def test2(): 44 time.sleep(3) 45 print("in the test2") 46 47 48 test1() 49 test2()
标签:and rand 源代码 mil 获取 分隔符 sleep soft 变量
原文地址:http://www.cnblogs.com/Druidchen/p/7906705.html