一:编写函数,(函数执行的时间用time.sleep(n)模拟)
import time
def num_func(x,y):
if x > y:
res = x-y
else:
res= y-x
time.sleep(2)
print(res)
return res
二:编写装饰器,为函数加上统计时间的功能
def timmer(func):
def wrapper(*args,**kwargs):
start = time.time()
res=func(*args,**kwargs)
end = time.time()
print(end-start)
return res
return wrapper
num_func = timmer(num_func)
num_func(2,5)
print(num_func)
三:编写装饰器,为函数加上认证的功能
def auth(func):
def wrapper(*args,**kwargs):
user_name = input('账号:>>').strip()
user_pwd = input('密码:>>').strip()
with open(r'db.txt','rb') as f:
while True:
msg = f.readline().decode('utf-8')
if not len(msg):
print('账号不存在')
return
if user_name in msg:
x,y = msg.strip().split(':')
if user_pwd == y:
res=func(*args,**kwargs)
print('成功')
return res
else:
print('账号密码错误')
return wrapper
num_func = auth(num_func)
num_func(1,6)
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
login_name = None
def atuh_func(func):
def wrapper(*args,**kwargs):
global login_name
if not login_name:
user_name = input('账号:>>').strip()
user_pwd = input('密码:>>').strip()
with open(r'db.txt','rb') as f:
while True:
msg = f.readline().decode('utf-8')
if not len(msg):
print('账号不存在')
return
x, y = msg.strip().split(':')
if user_name ==x:
if user_pwd == y:
res=func(*args,**kwargs)
print('成功')
login_name = user_name
return res
else:
print('账号密码错误')
else:
print('欢迎回来')
res = func(*args, **kwargs)
return res
return wrapper
num_func = atuh_func(num_func)
num_func(1,5)
num_func(1,5)
num_func(1,5)
num_func(1,5)
num_func(1,5)
num_func(1,5)
五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
login_name = None
num_time = 0
import time
def num_func(x,y):
if x > y:
res = x-y
else:
res= y-x
time.sleep(2)
print(res)
return res
def atuh_func(func):
def wrapper(*args,**kwargs):
global login_name
global num_time
if num_time > 5:
login_name = None
cmd = input('登录超时,输入‘P’请重新登录,其他键退出:>>').strip()
if cmd!='P':
return
if not login_name:
user_name = input('账号:>>').strip()
user_pwd = input('密码:>>').strip()
with open(r'db.txt','rb') as f:
while True:
msg = f.readline().decode('utf-8')
if not len(msg):
print('账号不存在')
return
x, y = msg.strip().split(':')
if user_name ==x:
if user_pwd == y:
start = time.time()
print('登录成功,开始计时')
res=func(*args,**kwargs)
login_name = user_name
end = time.time()
num_time = end -start
print(num_time)
return res
else:
print('账号密码错误')
else:
start1 = time.time()
print('欢迎回来')
res = func(*args, **kwargs)
end1 = time.time()
one_time = end1 - start1
num_time += one_time
return res
return wrapper
num_func = atuh_func(num_func)
num_func(1,5)
num_func(1,5)
num_func(1,5)
num_func(1,5)
num_func(1,5)
num_func(1,5)