python 多层装饰器
25、多层装饰器:
1、原理:执行顺序从上往下,#2和#3组成一个函数假设为nf1,#1和nf1组成一个函数nnf1
f1成为ck_ty_of_us的inner函数即nf1。nf1成为check_login的inner函数即nnf1。详细参照alex的多层装饰器讲解。。
#1 @check_login
#2 @ck_ty_of_us
#3 def f1():
pass
2、应用多层装饰器实现用户管理程序如下:
USER_LOGIN = {}
def check_login(func):
def inner(*args,**kwargs):
if USER_LOGIN.get('is_login'):
ret = func(*args,**kwargs)
return ret
else:
print('请先登录')
return inner
def ck_ty_of_us(func):
def inner(*args,**kwargs):
if USER_LOGIN['user_type'] == '2':
ret = func(*args,**kwargs)
return ret
else:
print('你没有权限')
return inner
def register(user,pwd):
with open('xinxi','r+') as f1:
f1.seek(0,2)
f1.write(user + '|' + pwd +'|1\n')
def login(user,pwd):
with open('xinxi','r+') as f5:
for line in f5:
if line.strip().startswith(user):
l2 = line.strip().split('|')
USER_LOGIN['is_login'] = True
USER_LOGIN['user_type'] = l2[2]
print('欢迎%s登陆' %user)
@check_login
@ck_ty_of_us#应用的是多层装饰器的功能。
def cpwd(user,pwd):
with open('xinxi','r+') as f2,open('xinxi2','w') as f3:
for line in f2:
if line.strip().startswith(user):
l1 = line.split('|')
l1[1] = pwd
line1 = '|'.join(l1)
f3.write(line1)
else:
f3.write(line)
@check_login
def viewmes(user):
#普通用户读取自己信息
list1 = []
with open('xinxi','r+') as f4:
for line in f4:
if line.strip().startswith(user):
list1.append(line.strip())
print(list1)
def main():
while True:
chose = input('1.注册 2.登陆 3.修改密码 4.查看自己的信息:')
if chose == '1':
username = input('请输入用户名:')
password = input('请输入密码:')
register(username,password)
if chose == '2':
username = input('请输入用户名:')
password = input('请输入密码:')
login(username,password)
if chose == '3':
username = input('请输入用户名:')
password = input('请输入要修改的密码:')
cpwd(username,password)
if chose == '4':
username = input('请输入用户名:')
viewmes(username)
main()