第1章 装饰器
1.1什么是装饰器?
装饰器就是用来为被装饰对象新增功能的工具/函数
1.2装饰器原则:
1. 不修改被装饰对象的源代码
2. 不修改被装饰对象的调用方式
1.3装饰器的目标:为被装饰对象加上新功能
import time
def index():
time.sleep(1)
print('index page')
def outter(func):
defwrapper():
start=time.time()
func()
stop=time.time()
print(stop - start)
returnwrapper
index=outter(index)
index()
第2章 装饰器语法糖:
在被装饰器对象正上方单独一行写:@装饰器的名字
import time
def outter(func):
defwrapper():
start=time.time()
func()
stop=time.time()
print(stop - start)
returnwrapper
@outter #index=outter(index)
def index():
time.sleep(1)
print('index page')
index()
2.1 装饰器修订:让装饰器可以装饰有参和无参函数
import time
def outter(func):
defwrapper(*args,**kwargs):
start=time.time()
res=func(*args,**kwargs)
stop=time.time()
print(stop - start)
return res
returnwrapper
@outter #index=outter(index)
def index():
time.sleep(1)
print('index page')
@outter
def home(name):
time.sleep(1)
print('home index')
index()
home('jiang')
2.2练习:在通过认证后,才能运行相关功能
import time
def outter(func):
defwrapper(*args,**kwargs):
start=time.time()
func(*args,**kwargs)
stop=time.time()
print(stop - start)
returnwrapper
def auth(func):
defwrapper(*args, **kwargs):
name=input('请输入用户名:').strip()
passwd=input('请输入密码:').strip()
ifname == 'jiang'and passwd == '123':
res=func(*args, **kwargs)
returnres
else:
print('认证失败')
returnwrapper
@auth
@outter #index=outter(index)
def index():
time.sleep(1)
print('index page')
@outter
def home(name):
time.sleep(1)
print('home index')
index()
第3章 叠加装饰器
加载顺序:自下而上
执行顺序:自上而下
import time
current_user={'username':None}
def timmer(func):
defwrapper(*args,**kwargs):
start=time.time()
res=func(*args,**kwargs)
stop=time.time()
print(stop-start)
returnres
returnwrapper
def auth(func):
defwrapper(*args,**kwargs):
ifcurrent_user['username']:
res=func(*args,**kwargs)
returnres
name=input('username>>: ').strip()
passwd=input('password>>: ').strip()
ifname == 'jiang'and passwd == '123':
current_user['username']=name
res=func(*args,**kwargs)
returnres
print('用户名或者密码错误')
returnwrapper
@timmer
@auth
def index():
print('from index')
@auth
def home():
print('from home')
index()
home()
第4章 有参装饰器:
import time
current_user={'username':None}
def outter(engine):
defauth(func):
defwrapper(*args,**kwargs):
ifcurrent_user['username']:
res=func(*args,**kwargs)
return res
name=input('username>>: ').strip()
passwd=input('password>>: ').strip()
ifengine == 'mysql':
if name == 'jiang'and passwd == '123':
current_user['username']=name
print('基于mysql的认证')
res=func(*args,**kwargs)
return res
else:
print('用户名或者密码不正确')
elifengine == "ldap":
print('基于ldap 的认证')
else:
print('基于文件的认证')
returnwrapper
returnauth
@outter(engine='mysql')
def index():
print('from index')
@outter(engine='ldap')
def home():
print('from home')
index()
home()
第5章 无参装饰器
import time
def timmer(func):
defwrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)
stop_time=time.time()
print('run time is %s' %(stop_time-start_time))
returnres
returnwrapper
@timmer
def foo():
time.sleep(1)
print('from foo')
foo()