Fork me on GitHub
# 一:编写函数,(函数执行的时间用time.sleep(n)模拟)
'''
import time
def info():
start_time = time.time()
time.sleep(3)
print('欢迎来到王者荣耀!')
stop_time=time.time()
print('run time is %s' %(stop_time-start_time))

info()
'''
# 二:编写装饰器,为函数加上统计时间的功能
'''
import time
def timer(func):
def wrapper(*args,**kwargs):
start_time = time.time()
res=func(*args,**kwargs)
stop_time = time.time()
print('run time is %s' % (stop_time - start_time))
return res
return wrapper
@timer
def info():
time.sleep(3)
print('欢迎来到王者荣耀!')

info()
'''
# 三:编写装饰器,为函数加上认证的功能
'''
def auth(func):
def wrapper(*args,**kwargs):
name=input('请输入用户名称: ').strip()
pwd=input('请输入用户密码: ').strip()
if name == 'tank' and pwd == '123':
res=func(*args,**kwargs)
return res
else:
print('账号或密码错误')
return wrapper

@auth
def index():
print('认证成功!')

index()
'''
# 四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
# 注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
'''
dic={}
def user_info(func):
def wrapper(*args,**kwargs):
with open('db.txt', mode='rt',encoding='utf-8')as f:
for line in f:
user,pwd,balance=line.strip().split(':')
dic[user]=[pwd, balance]
username=input('请输入用户名称:').strip()
password=input('请输入用户密码:').strip()
if username == user and password == dic[user][0]:
res=func(*args,**kwargs)
return res
else:
print('账号或密码错误!')
return wrapper

def incount():
print('充值功能!')

def outcount():
print('转账功能!')
@user_info
def users():
while True:
msg = "'0':'退出','1': '充值','2': '转账'"
print(msg)
cmd = input('请输入命令编号>>: ').strip()
if not cmd.isdigit():
print('必须输入命令编号的数字')
continue
elif cmd not in msg:
print('输入的命令不存在')
continue
else:
if cmd == '0':
break
elif cmd == '1':
incount()
elif cmd == '2':
outcount()

users()
'''
# 五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
'''
import time
dic={}
def user_info(func):
def wrapper(*args,**kwargs):
with open('db.txt', mode='rt',encoding='utf-8')as f:
for line in f:
user,pwd,balance=line.strip().split(':')
dic[user]=[pwd, balance]
username=input('请输入用户名称:').strip()
password=input('请输入用户密码:').strip()
if username == user and password == dic[user][0]:
res=func(*args,**kwargs)
return res
else:
print('账号或密码错误!')
return wrapper

def timer(func):
def wrapper(*args,**kwargs):
start_time = time.time()
res=func(*args,**kwargs)
stop_time = time.time()
times=stop_time - start_time
if times <= 1:
return res
else:
print('登录超时,请重新登录!')
return wrapper

@timer
def incount():
print('充值功能!')

@timer
def outcount():
print('转账功能!')

@user_info
def users():
while True:
msg = "'0':'退出','1': '充值','2': '转账'"
print(msg)
cmd = input('请输入命令编号>>: ').strip()
if not cmd.isdigit():
print('必须输入命令编号的数字')
continue
elif cmd not in msg:
print('输入的命令不存在')
continue
else:
if cmd == '0':
break
elif cmd == '1':
incount()
elif cmd == '2':
outcount()

users()
'''
posted on 2020-03-23 21:08  OBOS  阅读(142)  评论(0编辑  收藏  举报