# 一:编写函数,(函数执行的时间用time.sleep(n)模拟)
import time # 源码
def func():
time.sleep(3) # 单位: 秒
func()
# 二:编写装饰器,为函数加上统计时间的功能
import time
def timer(func):
def inner(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
end_time = time.time()
print(f'当前被装饰对象[{func.__name__}] 执行时间为: [{end_time - start_time}]')
return res
return inner
@timer
def func_demo():
time.sleep(3)
# 三:编写装饰器,为函数加上认证的功能
login_user = None
# 登录功能
def login():
username = input('请输入用户名: ').strip()
password = input('请输入密码: ').strip()
if username == 'tank' and password == '123':
print('登录成功')
global login_user
login_user = username
else:
print('登录失败')
# 登录认证装饰器
def login_auth(func):
def inner(*args, **kwargs):
if login_user:
res = func(*args, **kwargs)
return res
else:
print('未有用户登录,无法使用好玩的功能!')
login()
return inner
@login_auth
def play():
print('开始play了啊....')
pass
@login_auth
def shopping():
pass
# 四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
# 注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
with open('db.txt', 'r', encoding='utf-8') as f:
user_data = f.read()
user_dic = eval(user_data)
user_dic = user_dic
login_info = None
def login():
username = input('请输入用户名: ').strip()
if username in user_dic.get('name'):
password = input('请输入密码: ').strip()
if password == user_dic.get('pwd'):
print('login successful')
global login_info
login_info = {username: password}
else:
print('密码错误')
else:
print('用户不存在')
def login_auth(func):
def inner(*args, **kwargs):
if login_info:
res = func(*args, **kwargs)
return res
else:
login()
return inner
@login_auth
def withdraw():
pass
@login_auth
def shopping():
pass
# 五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
import time
sum_time = 0
def time_wait(func):
wait_time = 6
def inner(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
end_time = time.time()
global sum_time
# 第一个函数进来后,func1 执行时长为3, func2 执行时长为3
sum_time += (end_time - start_time)
print(f'登录后执行的总时长: {sum_time}')
if sum_time >= wait_time:
login()
sum_time = 0
else:
return res
return inner
@time_wait
def func1():
time.sleep(3)
@time_wait
def func2():
time.sleep(3)