通过一个任务来加深对装饰器的理解和应用
回顾:装饰器的框架
def timmer(func):
def wrapper():
func()
return wrapper
任务:给以下正在运行的程序加一个验证功能的装饰器正在运行的程序加一个验证功能的装饰器
def index():
print('欢迎来到京东主页')def home(name):
print('欢迎回家%s' %name)def shopping_car(name):
print('%购物车里有[%s,%s,%s]' %(name,'奶茶','蛋糕','娃娃'))
Step1:(初步实现一个人验证功能)
def check(func):
def wrapper(*args,**kwargs):
username = input('请输入用户名==>').strip()
passwd = input('请输入密码==>').strip()
if username == 'xhg' and passwd == '':
res = func(*args,**kwargs)
return res
else:
print('用户名或者密码错误,请重新登录')
return wrapper
@check
def index():
print('欢迎来到京东主页')
@check
def home(name):
print('欢迎回家%s' %name)
@check
def shopping_car(name):
print('%s购物车里有[%s,%s,%s]' %(name,'奶茶','蛋糕','娃娃')) index()
home('xhg')
shopping_car('xhg')
#上述程序可以实现基本功能
#缺点:每次执行一个函数时,均需要重新登录。
继续优化
Step2:(实现单个人在登录状态下验证一次)
current_user = {'username': None, 'passwd':False }
def check(func):
def wrapper(*args,**kwargs):
if current_user['username'] and current_user['passwd']:
res = func(*args, **kwargs)
return res
username = input('请输入用户名==>').strip()
passwd = input('请输入密码==>').strip()
if username =='xhg' and passwd == '':
current_user['username'] = username
current_user['passwd'] = True
res = func(*args,**kwargs)
return res
else:
print('用户名或者密码错误,请重新登录')
return wrapper
@check
def index():
print('欢迎来到京东主页')
@check
def home(name):
print('欢迎回家%s' %name)
@check
def shopping_car(name):
print('%s购物车里有[%s,%s,%s]' %(name,'奶茶','蛋糕','娃娃')) index()
home('xhg')
shopping_car('xhg')
#缺点:显示生活中并不可能只有一个用户,要考虑多个用户的情况
继续优化
step3:(登录状态与数据库进行匹配,并在登录状态下验证一次)
user_list=[
{'name':'a','passwd':''},
{'name':'b','passwd':''},
{'name':'c','passwd':''},
{'name':'d','passwd':''},
]
current_user = {'username': None, 'login': False}
def check(func):
def wrapper(*args,**kwargs):
if current_user['username'] and current_user['login']:
res = func(*args,**kwargs)
return res
username = input('请输入用户名==>').strip()
passwd = input('请输入密码==>').strip()
for user in user_list:
if username == user['name'] and passwd == user['passwd']:
current_user['username'] = username
current_user['login'] = True
res = func(*args,**kwargs)
return res
else:
print('用户名或者密码输入错误,请重新输入')
return wrapper
@check
def index():
print('欢迎来到京东主页')
@check
def home(name):
print('欢迎回家%s'%name)
@check
def shopping_car(name):
print('%s购物车里有[%s,%s,%s]'%(name, '奶茶', '蛋糕', '娃娃'))
index()
home(current_user['username'])
shopping_car(current_user['username'])
#感想:
当拿到一个要求,不要急于一下子写出完美的程序。要不断去思考、去联想、去调试。去想象还有什么需要完善的地方
自己还是练得少
以后要多加练习