33-0-装饰器版博客园
2020年12月14日大约 2 分钟
装饰器版一:
msg = """
1.请登录
2.请注册
3.进入文章页面
4.进入评论页面
5.进入日记页面
6.进入收藏页面
7.注销账号
8.退出整个程序
>>>
"""
login_dic = {
"username":None,
"flag":False,
"count":3
}
def wrapper(func):
def inner(*args,**kwargs):
if login_dic["flag"]:
func()
else:
while login_dic["count"]:
user = input("username:")
pwd = input("password:")
if user == "alex" and pwd == "alex123":
login_dic["username"] = user
login_dic["flag"] = True
login_dic["count"] = 0
print("登录成功!")
func()
else:
login_dic["count"] -= 1
print(f"用户名或密码错误!剩余次数{login_dic['count']}")
return inner
def register():
pass
@wrapper
def login():
pass
@wrapper
def article():
print("这是文章")
@wrapper
def comment():
print("这是评论")
@wrapper
def log():
print("这是日记")
@wrapper
def collect():
print("这是收藏")
@wrapper
def out():
login_dic["username"] = None
login_dic["flag"] = False
print("退出成功!")
func_dic = {
"1":login,
"2":register,
"3":article,
"4":comment,
"5":log,
"6":collect,
"7":out,
"8":exit,
}
while True:
chose = input(msg)
if chose in func_dic:
login_dic["count"] = 3
if chose == "1":
login()
else:
func_dic[chose]()
else:
print("请正确输入内容!")
装饰器版二:
msg = """
1.请登录
2.请注册
3.进入文章页面
4.进入评论页面
5.进入日记页面
6.进入收藏页面
7.注销账号
8.退出整个程序
>>>
"""
login_dic = {
"username":None,
"flag":False,
"count":3
}
def wrapper(func):
def inner(*args,**kwargs):
if login_dic["flag"]:
func()
else:
login(func)
return inner
def register():
pass
def login(func=False):
while login_dic["count"]:
user = input("username:")
pwd = input("password:")
if user == "alex" and pwd == "alex123":
login_dic["username"] = user
login_dic["flag"] = True
login_dic["count"] = 0
print("登录成功!")
if func:
func()
else:
login_dic["count"] -= 1
print(f"用户名或密码错误!剩余次数{login_dic['count']}")
@wrapper
def article():
print("这是文章")
@wrapper
def comment():
print("这是评论")
@wrapper
def log():
print("这是日记")
@wrapper
def collect():
print("这是收藏")
@wrapper
def out():
login_dic["username"] = None
login_dic["flag"] = False
print("退出成功!")
func_dic = {
"1":login,
"2":register,
"3":article,
"4":comment,
"5":log,
"6":collect,
"7":out,
"8":exit,
}
while True:
chose = input(msg)
if chose in func_dic:
login_dic["count"] = 3
func_dic[chose]()
else:
print("请正确输入内容!")
个人比较偏向第二种写法,因为这样就可以在装饰器中添加多个额外的功能,可读性还高