1,简单的装饰器
-
USER_INFO = {} #定义全局变量,据此来判断是否登录成功
-
-
-
def outer(func):
-
def inner(*args, **kwargs):
-
if USER_INFO.get("is_login", None): #先判断用户时候登录成功
-
r = func(*args,**kwargs)
-
return r
-
else: #登录不成功,则提示用户先登录
-
print("请先登录")
-
return inner
-
-
-
def login(user, pwd):
-
if user == "alex" and pwd == "123456":
-
print("欢迎%s光临!" % (user,))
-
USER_INFO["is_login"] = True
-
return True
-
else:
-
print("用户名或者密码错误!")
-
-
-
@outer
-
def balance():
-
print("\n你的余额为:3000元整\n")
-
-
-
@outer
-
def point():
-
print("\n你的积分为:18000\n")
-
-
-
@outer
-
def personal_info():
-
print("\n你的个人信息为:xxxxxx\n")
-
-
-
def main():
-
while True:
-
res = input("1,登录 2,积分查询 3,余额查询 4,个人信息查询\n请输入选择>>>")
-
if res == "1":
-
username = input("请输入用户名:")
-
password = input("请输入密码:")
-
login(username, password)
-
elif res == "2":
-
point()
-
elif res == "3":
-
balance()
-
elif res == "4":
-
personal_info()
-
else:
-
print("输入错误!请重新输入")
-
main()
2,多层装饰器
-
USER_INFO = {} #判断是否登录成功
-
USER_TYPE = {} #判断用户类型,是不是超级管理
-
-
-
def check_login(func):
-
def inner(*args, **kwargs):
-
if USER_INFO.get("is_login", None):
-
r = func(*args, **kwargs)
-
return r
-
else:
-
print("请先登录")
-
return inner
-
-
-
def check_admin(func):
-
def inner(*args, **kwargs):
-
if USER_TYPE.get("type", None) == 2:
-
r = func(*args, **kwargs)
-
return r
-
else:
-
print("你不是超级管理员,无权限!")
-
return inner
-
-
-
def login(user, pwd):
-
if user == "alex" and pwd == "123":
-
print("欢迎%s光临!" % (user,))
-
USER_INFO["is_login"] = True
-
USER_TYPE["type"] = 1
-
elif user == "admin" and pwd == "123":
-
print("欢迎%s光临!" % (user,))
-
USER_INFO["is_login"] = True
-
USER_TYPE["type"] = 2
-
else:
-
print("用户名或者密码错误!")
-
-
-
@check_login
-
def balance():
-
print("\n你的余额为:3000元整\n")
-
-
-
@check_login
-
def point():
-
print("\n你的积分为:18000\n")
-
-
-
@check_login --------->首先判断是否登录成功,然后再次判断是否为管理员
-
@check_admin
-
def admin():
-
print("你是超级管理员!")
-
-
-
def main():
-
while True:
-
res = input("1,登录 2,积分查询 3,余额查询 4,超级管理员\n请输入选择>>>")
-
if res == "1":
-
username = input("请输入用户名:")
-
password = input("请输入密码:")
-
login(username, password)
-
elif res == "2":
-
point()
-
elif res == "3":
-
balance()
-
elif res == "4":
-
admin()
-
else:
-
print("输入错误!请重新输入")
-
-
main()
多层装饰器。类似
还有更牛逼的装饰器以后web程序中会讲到,类似于@outer(before,after)
阅读(1381) | 评论(0) | 转发(0) |