login_dic = {"username": None, "flag": False}
msg = """请选择app:
QQ
微信
抖音
邮箱
"""
chose = input(msg).upper()
def auth(argv):
def wrapper(f):
def inner(args,**kwargs):
if login_dic["flag"]:
f(args,kwargs)
else:
if argv == "QQ":
print("欢迎登陆QQ")
user = input("请输入账号:")
password = input("请输入密码:")
if user == "alex" and password == "alex123":
login_dic["flag"] = True
login_dic["username"] = user
f(*args,kwargs)
else:
print("账号或者密码错误")
elif argv == "微信":
print("欢迎登陆微信")
user = input("请输入账号:")
password = input("请输入密码:")
if user == "alex123" and password == "alex123456":
login_dic["flag"] = True
login_dic["username"] = user
f(args, **kwargs)
else:
print("账号或者密码错误")
elif argv == "抖音":
print("欢迎登陆抖音")
user = input("请输入账号:")
password = input("请输入密码:")
if user == "alex456" and password == "alex456123":
login_dic["flag"] = True
login_dic["username"] = user
f(args, **kwargs)
else:
print("账号或者密码错误")
else:
print("欢迎登陆邮箱")
user = input("请输入账号:")
password = input("请输入密码:")
if user == "alex@qq.com" and password == "alex123":
login_dic["flag"] = True
login_dic["username"] = user
f(*args, **kwargs)
else:
print("账号或者密码错误")
return inner
return wrapper
@auth(chose)
def foo():
print("这是一个被装饰的函数")
foo()
@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
@wrapper3
@wrapper2
@wrapper1
def foo():
print("这是一个被装饰的函数")
foo()
3
2
1
这是一个被装饰的函数
11
22
33