装饰器(=高阶函数+嵌套函数)
定义:本质是函数,为其他函数添加附加功能
原则:不能修改被装饰的函数的源代码和调用方式
1.函数即“变量”
2.高阶函数:
-
把一个函数名当作实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
-
返回值return中包含函数名(不修改被修改函数的调用方式)
1 def bar(): 2 time.sleep(3) 3 print('in the bar') 4 #装饰器 5 def test(func): 6 start_time=time.time() 7 func() #run bar 8 stop_time=time.time() 9 print('the func run time is %s' %(stop_time-start_time)) 10 test(bar) 11
3.嵌套函数
def log(func): def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper @log def now(): print('2015-3-25') now()