3.23作业
目录
一:编写函数,(函数执行的时间用time.sleep(n)模拟)
import time
def foo():
time.sleep(0.3)
print('welecome to foo')
二:编写装饰器,为函数加上统计时间的功能
import time
def timmer(foo):
def wrapper():
start=time.time()
foo()
end=time.time()
print('run foo time is %s'%(end-start))
return wrapper
@timmer
def foo():
time.sleep(0.3)
print('welecome to foo')
foo()
三:编写装饰器,为函数加上认证的功能
def login(foo):
def func():
name=input('your name:').strip()
pwd=input('your password:').strip()
if name == 'egon' and pwd == '123':
print('login successfully')
foo()
else:
print('user or password error')
return func
@login
def check_money():
print('查询余额功能')
# check_money=login(check_money)
check_money()
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
def outter(func):
def wrapper():
global login
if not login:
user = input('请输入账号:').strip()
pwd = input('请输入密码:').strip()
with open('db.txt','r',encoding='utf-8') as f:
for line in f:
d1 = eval(line.strip())
if user == d1['name'] and pwd == d1['password']:
print('登陆成功')
login = True
func()
break
else:
print('登陆失败')
else:
func()
return wrapper
@outter
def fun1():
print('提现功能')
@outter
def fun2():
print('转账功能')
@outter
def fun3():
print('特殊功能')
login = False
fun1()
fun2()
fun3()
五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
def outter(func):
def wrapper():
global login
if os.path.exists('login.txt'):
with open('login.txt','r',encoding='utf-8') as f1:
l = f1.read()
if float(l) < time.time():
login = False
if not login:
if os.path.exists('login.txt'):
os.remove('login.txt')
user = input('请输入账号:').strip()
pwd = input('请输入密码:').strip()
with open('tank.txt','r',encoding='utf-8') as f:
for line in f:
d1 = eval(line.strip())
if user == d1['name'] and pwd == d1['password']:
print('登陆成功')
with open('login.txt','w',encoding='utf-8') as f5:
f5.write(str(time.time() + 10))
login = True
func()
break
else:
print('登陆失败')
else:
func()
return wrapper
@outter
def fun1():
print('提现功能')
@outter
def fun2():
print('转账功能')
@outter
def fun3():
print('特殊功能')
login = False
import os,time
fun1()
fun2()
time.sleep(11)
fun3()
六:选做题,思考题(选做),叠加多个装饰器,加载顺序与运行顺序,可以将上述实现的装饰器叠加起来自己验证一下
@deco1 # index=deco1(deco2.wrapper的内存地址)
@deco2 # deco2.wrapper的内存地址=deco2(deco3.wrapper的内存地址)
@deco3 # deco3.wrapper的内存地址=deco3(index)
def index():
pass
def deco1(func):
def swapper():
func()
print(1)
return swapper
def deco2(func):
def swapper():
func()
print(2)
return swapper
def deco3(func):
def swapper():
func()
print(3)
return swapper
@deco1 # index=deco1(deco2.wrapper的内存地址)
@deco2 # deco2.wrapper的内存地址=deco2(deco3.wrapper的内存地址)
@deco3 # deco3.wrapper的内存地址=deco3(index)
def index():
pass
index()