装饰器:
* 高阶函数 + 嵌套函数 => 装饰器
<1>.:定义:本质是函数,(装饰其他函数)就是为其他函数添加新功能。
原则:a:不能修改被装饰的函数的源代码。
b:不能修改被装饰的函数的调用方式。
<2>.实现装饰器的知识储备:
1:函数即变量。
2:高阶函数
a,把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为期添加新功能)。
import time def bar(): time.sleep(3) print("in the bar") def test1(func): start_time=time.time() # print(func) func() stop_time=time.time() print("the bar run(func) time:%s" %(stop_time-start_time)) test1(bar)
b,返回值中包含函数名(不修改函数的调用方式)。
import time def bar(): time.sleep(3) print("in the bar") return True def test2(func): print(func) return func # print(test2(bar)) # print(test2(bar)) # print(test2(bar)) # test2(bar()) # bar() # print(bar()) # t = test2(bar) # print(t) # t() bar = test2(bar) bar()
<3>.嵌套函数。
def foo(): print("in the foo") def bar(): print("in the bar") bar() foo()
x=0 def grandpa(): x=1 def dad(): x=2 def son(): x=3 print(x) son() dad() grandpa()
<3>.使用装饰器
import time def deco(func): start_time = time.time() func() stop_time = time.time() print("the fun run time is %s" %(stop_time - start_time)) def test1(): time.sleep(3) print("in the test1") def test2(): time.sleep(3) print("in the test2") # test1() # test2() # deco(test1()) #test1的返回值 deco(test1) deco(test2)
import time def deco(func): start_time = time.time() return func stop_time = time.time() print("the fun run time is %s" %(stop_time - start_time)) def test1(): time.sleep(3) print("in the test1") def test2(): time.sleep(3) print("in the test2") # test1() # test2() # deco(test1()) #test1的返回值 # deco(test1) # deco(test2) test1 = deco(test1) test1() teat2 = deco(test2) test2()
import time def timer(func): def deco(): start_time = time.time() func() stop_time = time.time() print("the fun 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") test1 = timer(test1) test1() test2 = timer(test2) test2()
import time def timer(func): def deco(): start_time = time.time() func() stop_time = time.time() print("the fun run time is %s" %(stop_time - start_time)) return deco @timer #test1 = timer(test1) def test1(): time.sleep(3) print("in the test1") @timer #test2 = timer(test2) def test2(): time.sleep(3) print("in the test2") # test1 = timer(test1) test1() # test2 = timer(test2) test2()
import time def timmer(func): def deco(): start_time = time.time() func() stop_time = time.time() print("the time run is %s" %(stop_time - start_time)) return deco @timmer #test1 = timer(test1) def test1(): time.sleep(3) print("in the test1") test1()
in the test1 the time run is 3.0006814002990723
import time def timmer(func): def deco(*args, **kwargs): start_time = time.time() func(*args, **kwargs) stop_time = time.time() print("the time run is %s" %(stop_time - start_time)) return deco @timmer #test1 = timer(test1) def test1(*args, **kwargs): time.sleep(3) print("in the test1") test1()