day10-12-7装饰器语法糖、有参装饰器、叠加多个装饰器、warps装饰器
一:装饰器语法糖
定义:用"@"+ 函数,放在要被修饰的函数前,即可调用函数
实例
import time
def timmer(f):
def warpper(*args,**kwargs):
start=time.time
tes=f(*args,**kwargs)
stop=time.time
print("run time is %s"% (stop-start))
return tes
return warpper
@timmer
def index():
time.sleep(1)
print('form index')
index()
二、有参装饰器
1、无参装饰器模板
def outter(func):
def wrarper(*args,**kwargs):
res=func(*args,**kwargs)
return res
return wrarpper
2、有参装饰器模板
def add(x):
def outter(func):
def wrarper(*args,**kwargs):
res=func(*args,**kwargs)
return res
return warpper
return outter
3.实例
import time
def login(x,engine='file'):
def auth(func):
def wrarper(*args,**kwargs):
print("--------",x)
inp_user=input("username>>>: ").strip
inp_pwd=input("password>>>: ").strip
if engine == 'file':
print('基于file的认证')
if inp_user == "egon" and inp_pwd == "123":
print("login successful")
res=func(*args,**kwargs)
return res
else:
print('username or passwd is error')
elif engine == 'mysql':
print('基于mysql的认证')
elif engine == 'ldap':
print('基于ldap的认证')
else :
print('认证来源未知')
return wrarper
return auth
@login(12,engine='mysql')
def index():
time.sleep(1)
print('from index')
index()
三、叠加多个装饰器
实例
def outter1(func1): #func1=wrarper2的内存地址
print('---------outter1')
def wrarper1(*args, **kwargs):
print('--------wrarper1')
res1 = func1(*args, **kwargs)
return res1
return wrarper1
def outter2(func2): #func2=wrarper3的内存地址
print('---------outter2')
def wrarper2(*args, **kwargs):
print('--------wrarper2')
res2 = func2(*args, **kwargs)
return res2
return wrarper2
def outter3(func3): #func3=被装饰函数也就是index的地址
print('---------outter3')
def wrarper3(*args, **kwargs):
print('--------wrarper3')
res3 = func3(*args, **kwargs)
return res3
return wrarper3
#index=wrarper1的内存地址
@outter1 #outter1(wrarper2的内存地址)------------->wrarper1的内存地址
@outter2 #outter2(wrarper3的内存地址)------------->wrarper2的内存地址
@outter3 #outter3(被修饰函数也就是index的内存地址)--->wrarper3的内存地址
def index():
print('hello world')
index()
四、wraps装饰器
定义:from functools import wraps
实例:
import time
from functools import wraps
def timmer(func):
@wraps(func)
def wrarper(*args, **kwargs):
start = time.time()
res = func(*args, **kwargs)
stop = time.time()
print('run time is %s:' % (stop - start))
return res
return wrarper
@timmer
def index():
time.sleep(1)
print('hello world')
print(index)
print(index.__name__)
help(index)