函数闭包为函数加上认证功能
1.登陆账号
user_dic ={‘username‘:None,‘login‘:False} def auth_func(func): def wrapper(*args,**kwargs): if user_dic[‘username‘] and user_dic[‘login‘]: res = func(*args,**kwargs) return res username = input(‘账号:‘).strip() passwd = input(‘密码:‘).strip() if username == ‘abcd‘ and passwd == ‘123456‘: user_dic[‘username‘] = username user_dic[‘login‘] = True print(‘登陆成功!‘) res=func(*args,**kwargs) return res else: print(‘用户名或密码错误‘) return wrapper @auth_func def index(): print(‘欢迎光临本网站‘) @auth_func def home(name): print(‘欢迎%s回家‘ % name) index() home(‘小明‘)
运行结果:
账号:abcd 密码:123456 登陆成功! 欢迎小明回家 Process finished with exit code 0
2.检测已有账号登陆
user_list=[{‘name‘:‘abcd‘,‘passwd‘:‘123456‘}, {‘name‘:‘abd‘,‘passwd‘:‘123‘}, {‘name‘:‘acc‘,‘passwd‘:‘123456‘}, {‘name‘:‘asdfg‘,‘passwd‘:‘12346‘} ] user_dac ={‘username‘:None,‘login‘:False} # 获取刚开始登陆之前的状态 def auth_func(func): def wrapper(*args,**kwargs): if user_dac[‘username‘] and user_dac[‘login‘]: # 获取刚开始登陆之前的状态,是否已登录 res = func(*args,**kwargs) return res username = input(‘账号:‘).strip() passwd = input(‘密码:‘).strip() for user_dic in user_list: if username == user_dic[‘name‘] and passwd == user_dic[‘passwd‘]: user_dac[‘username‘] = username user_dac[‘login‘] = True print(‘登陆成功!‘) res=func(*args,**kwargs) return res else: print(‘用户名或密码错误‘) return wrapper @auth_func def index(): print(‘欢迎光临本网站‘) @auth_func def home(name): print(‘欢迎%s回家‘ % name) index() home(‘sb‘)
运行结果:
账号:abd 密码:123 登陆成功! 欢迎光临本网站 欢迎sb回家 Process finished with exit code 0
原文地址:https://www.cnblogs.com/liujinjing521/p/11218689.html
时间: 2024-10-12 17:01:42