python装饰器练习
Posted xiaomaotongxue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python装饰器练习相关的知识,希望对你有一定的参考价值。
装饰器的初步使用
需求:
1.登录京东
2.有3个页面home、finance、book
3.检测有没有登录,没登录调用登录接口
4.home使用京东自己的登录
5.finance用微信
6.book用微信登录
auth_type=‘jingdong‘
def login(auth_type, flag=False): def logged(f): def hadlog(*x, **y): f(*x, **y) return hadlog def choice(f): def jd(*x, **y): with open(‘jingdong‘, ‘r‘, encoding=‘utf8‘) as f1: dic = eval(f1.read()) username = dic[‘username‘] pwd = dic[‘pwd‘] while True: useid = input(‘请输入用户名:‘) usepwd = input(‘请输入密码:‘) if useid == username and usepwd == pwd: print(‘通过京东账号登录成功!‘) break else: print(‘用户名或密码错误,登陆失败!‘) flag = True f(*x, **y) def wx(*x, **y): with open(‘weixin‘, ‘r‘, encoding=‘utf8‘) as f1: dic = eval(f1.read()) username = dic[‘username‘] pwd = dic[‘pwd‘] while True: useid = input(‘请输入用户名:‘) usepwd = input(‘请输入密码:‘) if useid == username and usepwd == pwd: print(‘通过微信登录成功!‘) break else: print(‘用户名或密码错误,登陆失败!‘) flag = True f(*x, **y) if auth_type == ‘jd‘: return jd elif auth_type == ‘wx‘: return wx else: pass # 可增加其他登录方式 if flag == True: return logged if flag == False: return choice @login(‘jd‘) def home(): print(‘welcome to home page‘) @login(‘wx‘) def finance(): print(‘welcome to finance page‘) @login(‘wx‘) def book(): print(‘welcome to book page‘) home()
以上是关于python装饰器练习的主要内容,如果未能解决你的问题,请参考以下文章