目录
一、编写函数(函数执行的时间用time.sleep(n)模拟)
import time
def time_sleep(n):
print("函数开始")
time.sleep(n)
print("函数结束")
time_sleep(1)
二、编写装饰器,为函数加上统计时间的功能
import time
def timmer(func):
def outter(*args,**kwargs):
start = time.time()
func(*args,**kwargs)
stop = time.time()
print(stop - start)
return outter
@timmer
def time_sleep(n):
print("函数开始")
time.sleep(n)
print("函数结束")
time_sleep(1)
三、编写装饰器,为函数加上认证的功能
def login(func):
"""登录装饰器"""
def wrapper(*args,**kwargs):
name_inp = input("请输入你的用户名:")
pwd_inp = input("请输入你的密码:")
with open("a.txt","r",encoding="utf-8") as f:
for line in f :
name,password = line.strip().split(":")
if name ==name_inp and password == pwd_inp:
print("登录成功")
func(*args,**kwargs)
return
else:
print("输入错误")
return wrapper
@login
def eat(n):
"""吃东西"""
print(f"吃{n}吨屎")
eat(100)
四、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
is_login = False
def judge_login(login_user):
def login(func):
def wrapper(*args,**kwargs):
if not login_user:
name_inp = input("请输入你的用户名:")
pwd_inp = input("请输入你的密码:")
with open("a.txt","r",encoding="utf-8")as f :
for line in f:
name,pwd = line.strip().split(":")
if name == name_inp and pwd_inp == pwd:
print("登录成功")
func(*args,**kwargs)
global is_login
is_login = True
break
else:
print("登录失败")
else:
func(*args,**kwargs)
return wrapper
return login
@judge_login(is_login)
def eat_chicken(n):
'''吃鸡腿'''
print(f"吃{n}个鸡腿")
eat_chicken(1)
@judge_login(is_login)
def eat_chocolates(m):
'''吃巧克力'''
print(f"吃{m}个巧克力")
eat_chocolates(2)
五、编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
import time
user_list={"name" : None, "password":None ,"now":None,"timeout":5}
def login(func):
def wrapper(*args,**kwargs):
if user_list['name']:
timeout = time.time() - user_list['timeout']
if timeout < user_list['now']:
return func(*args, **kwargs)
else:
print("已超时")
name_inp = input("请输入你的用户名:")
pwd_inp = input("请输入你的密码:")
if name_inp == "hz" and pwd_inp == "123":
print("登录成功")
user_list["name"]=name_inp
user_list["password"]=pwd_inp
user_list["now"]=time.time()
func(*args,**kwargs)
else:
print("登录失败")
return wrapper
@login
def eat_chicken(n):
'''吃鸡腿'''
time.sleep(2)
print(f"吃{n}个鸡腿")
eat_chicken(1)
@login
def eat_chocolates(m):
'''吃巧克力'''
print(f"吃{m}个巧克力")
time.sleep(3)
eat_chocolates(2)
@login
def eat_pig(n):
print(f"吃{n}头猪")
eat_pig(1000)