装饰器
装饰器:本身就是函数,功能是为其他函数添加附加功能
原则:
1.不修改被修饰函数的源代码
2.不修改被修饰函数的调用方法
从结构来看,装饰器 = 高阶函数 + 函数嵌套 + 闭包
高阶函数:参数或返回值是一个函数
import time
def foo():
time.sleep(0.5)
print('hello')
def test(func):
print(func)
start_time=time.time()
func()
stop_time=time.time()
print('运行时间是%s'%( stop_time-start_time))
return func #func并没有修改就直接返回
foo=test(foo) #运行了一次test函数,foo函数作为返回值被赋给变量foo
foo() #等于又执行了一次foo函数
<function foo at 0x0000000003BD2378>
hello
运行时间是0.5
hello
以上,直接通过高阶函数返回未修改的原函数并没有什么意义,再赋给原来的变量名,更无意义。so高阶函数并没有办法直接作为装饰器
函数嵌套:函数内定义一个新的函数
闭包:函数作用域的一种体现,嵌套函数运行时从自己封装的变量找,找不到再往外找。外层传入的变量可以给内层函数使用
import time
def foo():
time.sleep(0.5)
print('hello')
def timer(func):
def wrapper(*args,**kwargs): #传入参数
start_time=time.time()
res = func(*args,**kwargs) #res接收func返回值
end_time = time.time()
print('运行时间是%s'%(end_time - start_time))
return res # wrapper运行后返回res
return wrapper
#foo = timer(foo) #相当于@timer
# foo()
@timer #语法糖
def foo(name,age):
time.sleep(0.5)
print('hello','名字是%s年龄是%s'%(name,age))
return 1
res = foo('bob',18)
print(res)
hello 名字是bob年龄是18
运行时间是0.5
1