---Restore content begins---
Definition of a closure: an inner function references a variable of an outer function
Application of Closures: Decorators
Why is there a decorator: a decorator can add functions before and after the original function without changing the way the original function is called
#Advanced decorator, applying a new function can globally control whether all decorators take effect.
import time FLAG = True def outer(flag): def timmer(f): def inner(*args,**kwargs): if flag == True: start_time = time.time() ret = f (* args, ** kwargs) end_time = time.time() print(end_time - start_time) else: ret = f (* args, ** kwargs) return ret return inner return timmer @outer(FLAG) # func = timmer(func) def func(a,b): print('begin func,a',a) time.sleep(0.3) print('end func,b',b) func(1,2)
#Decorator login log login_info = { ' alex ' :False} def login(func): def inner(name): if login_info[name] != True: user = input('user : ') pwd = input('pwd : ') if user == 'alex' and pwd == 'alex123': login_info[name] = True if login_info[name] == True: ret = func(name) return ret return inner @login def index(name): print('welcome %s to index' %name) index('alex')
#Multiple decorators decorate a function, you need to put the decorator that executes first in it to execute first.
1 def wrapper1(func): 2 def inner(): 3 print ' w1,before ' 4 func() 5 print ' w1,after ' 6 return inner 7 8 def wrapper2(func): 9 def inner(): 10 print ' w2,before ' 11 func() 12 print ' w2,after ' 13 return inner 14 15 @wrapper2 16 @wrapper1 17 def foo(): 18 print 'foo' 19 20 foo() 21 22 运行结果: 23 w2,before 24 w1,before 25 foo 26 w1,after 27 w2,after