import time def timer(func): def inner(*args,**kwargs): start = time.time() re = func(*args,**kwargs) print(time.time() - start) return re return inner @timer #==> func1 = timer(func1) def func1(a,b): print('in func1') @timer #==> func2 = timer(func2) def func2(a): print('in func2 and get a:%s'%(a)) return 'fun2 over' func1('aaaaaa','bbbbbb') # 带参装饰器理解过程。 --> func1 = timmer(func1) ---> func1("aaaaaa',"bbbbbb") print(func2('aaaaaa')) def auth(driver='file'): def auth2(func): def wrapper(*args,**kwargs): name=input("user: ") pwd=input("pwd: ") if driver == 'file': if name == 'egon' and pwd == '123': print('login successful') res=func(*args,**kwargs) return res elif driver == 'ldap': print('ldap') return wrapper return auth2 @auth(driver='file') # 这里在用@注解的时候,auth(driver='file') ,加了括号,就是执行的意思,并传了参娄,已经反回了 auth2函数,相于foo函数,被 auth2直接装饰了 def foo(name): print(name) foo('egon') # 因此调用时----> foo=auth2(foo) ----> foo('egon')
def auth(driver='file'):
def auth2(func):
def wrapper(*args,**kwargs):
name=input("user: ")
pwd=input("pwd: ")
if driver == 'file':
if name == 'egon' and pwd == '123':
print('login successful')
res=func(*args,**kwargs)
return res
elif driver == 'ldap':
print('ldap')
return wrapper
return auth2
@auth(driver='ldap') # 这里改变传参 driver='ldap' # 这里在用@注解的时候,auth(driver='file') ,加了括号,就是执行的意思,并传了参娄,已经反回了 auth2函数,相于foo函数,被 auth2直接装饰了
def foo(name):
print(name)
foo('egon') # 因此调用时----> foo=auth2(foo) ----> foo('egon') (如果装饰的不带参的函数,就是foo() )