再这两个函数的前面加上@timmer,index()和home(name)函数就相当于被注入了计时功能,现在只需要调用index()和home(‘yuan’),它就已经变身为‘新功能更多的函数了。’
所以这里的装饰器就像一个注入的符号:有了它,拓展了原来函数的功能既不需要侵入函数内更改代码,也不需要重复执行原函数。
用装饰器来实现认证功能:
import time
current_user={
'username':None,
#'login_time':None
}
def auth(func):
# func = index
def wrapper(*args,**kwargs):
if current_user['username']:
print('已经登录过了')
res=func(*args,**kwargs)
return res
uname = input('输入用户名:').strip()
pwd = input('密码:').strip()
if uname == 'linuxmi' and pwd == '123':
print('登录成功')
current_user['username']=uname
res = func(*args,**kwargs)
return res
else:
print('用户名或密码错误')
return wrapper
@auth #index = auth(index)
def index():
time.sleep(1)
print('welcom to index page')
@auth
def home(name):
time.sleep(2)
print('welcome %s to home page'%name)
input()
home('linuxmi')
有参数的装饰器来用于用户认证
import time
current_user={
'username':None,
# 'login_time':None
}
def auth(func):
# func=index
def wrapper(*args,**kwargs):
if current_user['username']:
print('已经登陆过了')
res=func(*args,**kwargs)
return res
uname=input('用户名>>: ').strip()
pwd=input('密码>>: ').strip()
if uname == 'linuxmi' and pwd == '123':
print('登陆成功')
current_user['username']=uname
res=func(*args,**kwargs)
return res
else:
print('用户名或密码错误')
return wrapper
def timmer(func):
def wrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)
stop_time=time.time()
print(stop_time-start_time)
return res
return wrapper
@timmer # timmer 统计的是auth+index的执行时间
@auth
def index():
time.sleep(1)
print('welcome to index page')
return 122
index()
叠加多个装饰器:
import time
current_user={
'username':None,
# 'login_time':None
}
def auth(func):
# func=index
def wrapper(*args,**kwargs):
if current_user['username']:
print('已经登陆过了')
res=func(*args,**kwargs)
return res
uname=input('用户名>>: ').strip()