知识储备
由于语法糖的的限制,outter函数只能有一个参数,并且该参数只能用来接收被装饰对象的内存地址
有参函数
就是利用函数嵌套的方式,把写好功能的参数用函数在包起来,强行给原函数写个爹再加个爷,通过他爷调他爹再找他,达到截胡的目的。
def outter(func,x):
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
return res
return wrapper
@outter # index=outter(index)
def index(x, y):
print(x, y)
index(1, 2)
需求:编写一个登陆认证的小例子
def auth(db_type):
def deco(func):
def wrapper(*args, **kwargs):
name = input('your bnae>>>: ').strip()
pwd = input('your pwd>>>: ').strip()
if db_type == 'file':
print('基于文件验证')
if name == 'dls' and pwd == 'dls123':
print('登录成功')
res = func(*args, **kwargs)
return res
else:
print('账号密码错误')
elif db_type == 'mysql':
print('基于mysql认证')
elif db_type == 'ldap':
print('基于ldap验证')
else:
print('不支持其他类型获取')
return wrapper
return deco
deco = auth(db_type='file')
@deco # 账号密码的来源是文件
def index(x, y):
print('index->>%s:%s' % (x, y))
index(1, 2)
deco = auth(db_type='mysql')
@deco # 账号密码的来源是数据库
def index(x, y):
print('index->>%s:%s' % (x, y))
index(1, 2)
# 账号密码的来源是ldap
deco = auth(db_type='ldap')
@deco
def index(x, y):
print('index->>%s:%s' % (x, y))
index(1, 2)
为什么需要嵌套三层,需求是wrapper内需要参数了,而我们又不能通过wrapper内参数传参在外面
套了一层deco又因为函数用了语法糖不能传参,我们又在外面套了一层auth有参装饰器。其实有了第三层以后无论在函数体那个
地方加参数都可以用auth传值就不需要在套第四层了,因为第三层不受一二层的限制,第三层可以灵活传参。
def auth(db_type):
def deco(func):
def wrapper(*args, **kwargs):
name = input('your bnae>>>: ').strip()
pwd = input('your pwd>>>: ').strip()
if db_type == 'file':
print('基于文件验证')
if name == 'dls' and pwd == 'dls123':
print('登录成功')
res = func(*args, **kwargs)
return res
else:
print('账号密码错误')
elif db_type == 'mysql':
print('基于mysql认证')
elif db_type == 'ldap':
print('基于ldap验证')
else:
print('不支持其他类型获取')
return wrapper
return deco
@auth(db_type='file') # 账号密码的来源是文件
def index(x, y):
print('index->>%s:%s' % (x, y))
index(1, 2)
@auth(db_type='mysql') # 账号密码的来源是数据库
def index(x, y):
print('index->>%s:%s' % (x, y))
index(1, 2)
@auth(db_type='ldap') # 账号密码的来源是ldap
def index(x, y):
print('index->>%s:%s' % (x, y))
index(1, 2)
有参装饰器模板
def auth(x):
def outter(func):
def wrapper(*args,**kwargs):
res=func(*args,**kwargs)
#调用原函数
# 为其增加新功能
return res
return wrapper
return outter
@auth(x)
def x():
pass