装饰器(二)
1.有参装饰器
在装饰器的基础上在套一层
lodic_dic = {"username":None,"flag":False}
msg = '''
QQ
微信
抖音
邮箱
请输入你要选择登陆的app:
'''
chose = input(msg).upper()
def auth(argv):
def wrapper(func):
def inner(*args,**kwargs):
if logic_dic["flag"]:
func(*args,**kwargs)
else:
if argy == "QQ":
print("欢迎登陆QQ")
user = input("username:")
pwd = input("password:")
if user =="alex",and pwd == "alex123":
logic_dic["flag"] = True
logic_dic["username"] = user
func(*args,**kwargs)
else:
print("用户名或密码错误")
elif argv == "微信":
print("欢迎登陆微信")
user = input("username:")
pwd = input("password:")
if user == "wusir" and pwd =="wusir123":
logic_dic["flag"] = True
logic_dic["username"] = user
func(*args,**kwargs)
else:
print("用户名或密码错误")
elif argv == "抖音":
print("来了,老弟")
user = input("username:")
pwd = input("password:")
if user == "alex" and pwd == "lexa":
logic_dic["flag"] = True
logic_dic["username"] = user
func(*args,**kwargs)
else:
print("用户名或密码错误")
else:
print("欢迎登陆邮箱")
user = input("username:")
pwd = input("password:")
if user== "alex@qq.com" and pwd =="ale":
logic_dic["flag"] = True
logic_dic["username"] = user
func(*args,**kwargs)
else:
print("用户名或密码错误")
return inner
return wrapper
@auth("QQ")
def foo():
print("这是一个被装饰的函数")
@auth(chose) 相当于以下两行代码的解构
wrapper = auth(chose)
foo = wrapper(foo)
2.多个装饰器装饰一个函数
被装饰的函数正上方有多个装饰器,先执行离被装饰函数最近的装饰器
def wrapper1(func):
def inner1(*args,**kwargs):
print(1)
func(*args,**kwargs)
print(11)
return inner1
def wrapper2(func):
def inner2(*args,**kwargs):
print(2)
func(*args,**kwargs)
print(22)
return inner2
def wrapper3(func):
def inner3(*args,**kwargs):
print(3)
func(*args,**kwargs)
print(33)
return inner3
@wrapper1
@wrapper2
@wrapper3
def foo():
print("这是一个被装饰的函数")
foo()
解析:
foo = wrapper3(foo) # foo = inner3
foo = wrapper2(foo) # foo = wrapper2(inner3) foo==inner2
foo = wrapper1(foo) # foo = wrapper1(inner2)
# 1 2 3 这是一个被装饰的函数 3 2 1
小技巧:进入装饰器从下往上,走到最后一个装饰器执行被装饰的函数,退出装饰器从下往上走