装饰器:本质是函数,用于装饰其他函数,为其他函数添加附加功能
原则:
1.不能比修改被装饰的函数的代码
2.不能修改被装饰的函数的调用方式
import time def timmer(func): def warpper(*args,**kwargs): start_time=time.time() func() stop_time=time.time() print(start_time,stop_time) return warpper() @timmer def test1(): time.sleep(3) print('I am test1 !!!!!')
执行结果:
I am test1 !!!!!
1520652510.288641 1520652513.2888126
实现装饰器知识储备:
装饰器=高阶函数+嵌套函数
1.函数即“变量”
2.高阶函数
a.把一个函数名当作形参传给另外一个函数(在不修改被装饰函数源代码的情况下,为其添加功能)
b.返回值中包含函数名(不修改函数的调用方式)
3.嵌套函数
1.函数即"变量"
def foo(): print('in the foo !!!') bar() def bar(): print('I am bar !!!') foo()
执行结果:
in the foo !!!
I am bar !!!
def bar(): print('in the bar !!!') def test1(func): print(func) test1(bar)
执行结果:
<function bar at 0x01E54228>
def bar(): print('in the bar') def test1(func): print(func) func() test1(bar)
执行结果:
<function bar at 0x02104228>
in the bar
import time def bar(): print('in the bar !!!') def test1(func): start_time=time.time() func() stop_time=time.time() print('in the fun !!!') print(start_time,stop_time) test1(bar)
执行结果:
in the bar !!!
in the fun !!!
1520656155.743149 1520656155.743149
import time def bar(): time.sleep(3) def test2(func): print(func) return func print (test2(bar))
执行结果:
<function bar at 0x005C4228>
<function bar at 0x005C4228>
import time def bar(): time.sleep(3) def test2(func): print(func) return func print (test2(bar)) t=test2(bar) print(t)
执行结果:
<function bar at 0x01DF4228>
<function bar at 0x01DF4228>
<function bar at 0x01DF4228>
<function bar at 0x01DF4228>
import time def bar(): time.sleep(3) print('in the bar !!!') def test2(func): print(func) return func bar=test2(bar) bar()
执行结果:
<function bar at 0x00714228>
in the bar !!!
def foo(): print('in the foo') def bar(): print('in the bar') bar() foo()
运行结果:
in the foo
in the bar
import time def deco(func): start_time=time.time() func() stop_time=time.time() def test1(): time.sleep(3) print('in the test1') def test2(): time.sleep(3) print('in the test2') #deco(test1) test1=deco(test1) #deco(test2) test2=deco(test2)
in the test1
in the test2
import time def timer(func): def deco(): start_time=time.time() func() stop_time=time.time() print(start_time,stop_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() #--->执行deco()函数
运行结果:
<function timer.<locals>.deco at 0x005841E0>
import time def timer(func): def deco(): start_time=time.time() func() stop_time=time.time() print(start_time,stop_time) return deco @timer # 等同于 test1=timer(test1) def test1(): time.sleep(3) print('in the test1') def test2(): time.sleep(3) print('in the test2') test1()
运行结果:
in the test1
1520663936.4761815 1520663939.476353