装饰器

高阶函数加嵌套函数=装饰器

# _*_coding:utf-8_*_
# Author:len liu
import time

def bar():
# start_time=time.time()
time.sleep(1)
print('in the bar')
# stop_time=time.time()

# print('use time %s ' %use_time) #bar() -------------->

                                                #in the bar
                                                #use time 1.000830888748169



def timer(fun):
def add_use_time():
start_time=time.time()
fun()
stop_time=time.time()
print('use time %s ' %(stop_time - start_time))
return add_use_time

bar=timer(bar)
bar()
#--------------> #in the bar
          #use time 1.000830888748169


语法糖:
import time
def timer(fun):
def new_bar():
start_time=time.time()
fun()
stop_time=time.time()
print("use time is %s" %(stop_time - start_time))
return new_bar
#bar=timer(bar)
@timer #语法糖,装饰函数要写在被装饰函数的上面,否则会出现not define
def bar():
time.sleep(1)
print('in the bar')

bar()
-------------------------------------------------------------------
装饰器在装饰的函数无参数和任意参数的情况下,添加*args和**kwargs来实现,bar和bar1相当于new_bar,只需将参数添加到new_bar,即添加了传参!
import time
def timer(fun):
def new_bar(*args,**kwargs):
start_time=time.time()
fun(*args,**kwargs)
stop_time=time.time()
print("use time is %s" %(stop_time - start_time))
return new_bar
#bar=timer(bar)
@timer
def bar():
time.sleep(1)
print('in the bar')
@timer
def bar1(**kwargs):
time.sleep(1)
print(kwargs)

bar()
bar1(name='lenn',age='15')
----------------------------------------------------------------------
有参装饰器:

可以在函数外再添加一层函数,给该最外层函数添加参数传给里面的函数达到装饰器传参

import time

current_userinfo={'user':None}

def auth(engine='file'):
def outter(func): #func=最原始的index
def wrapper(*args,**kwargs):
if engine == 'file':
if current_userinfo['user']:
return func(*args,**kwargs)
user=input('please input you username: ').strip()
pwd=input('please input you password: ').strip()
if user == 'lenn' and pwd == '123':
print('login successfull')
# 保存登录状态
current_userinfo['user']=user
res=func(*args,**kwargs)
return res
else:
print('user or password err')
elif engine == 'mysql':
print('mysql 的认证机制')
elif engine == 'ldap':
print('ldap 的认证机制')
else:
print('不支持该engine')
return wrapper
return outter

@auth(engine='mysql') #@outter # index=outter(最原始的index) # index= wrapper
def index():
print('welcome to index page')
time.sleep(3)

@auth(engine='ldap')
def home(name):
print('welecom %s ' %name)
time.sleep(2)
return 123

index() #warpper()
home('lenn') #wrapper('lenn')

 

----------------------------------------------------------------------------------------------------------

装饰器套装饰器

 

import time

current_userinfo={'user':None}

def timmer(func): #func=最原始的index指向的内存地址
def wrapper2(*args,**kwargs):
print('wrapper2.....')
start=time.time()
res=func(*args,**kwargs) # func=最原始的index指向的内存地址
stop=time.time()
print('run time is %s' %(stop - start))
return res
return wrapper2

def outter(func): # func=wrapper2
def wrapper1(*args,**kwargs):
print('wrapper1.....')
if current_userinfo['user']:
return func(*args,**kwargs)
user=input('please input you username: ').strip()
pwd=input('please input you password: ').strip()
if user == 'lenn' and pwd == '123':
print('login successfull')
# 保存登录状态
current_userinfo['user']=user
res=func(*args,**kwargs) # func=wrapper2
return res
else:
print('user or password err')
return wrapper1


# 解释语法的时候应该自下而上
# 执行时则是自上而下
# 可以连续写多个装饰器,处于最顶层的装饰器先执行
@outter # index=outter(wrapper2) # index=wrapper1
@timmer # timmer(最原始的index指向的内存地址) ==>wrapper2
def index():
print('welcome to index page')
time.sleep(3)


index() #wrapper1()



posted @ 2018-07-16 21:54  len1028  阅读(106)  评论(0编辑  收藏  举报