import time
defdemo1(*args,**kwargs):
time.sleep(0.2)for i in args:print("index1-----------{}".format(i), end="\t")print()for k, v in kwargs.items():print("index2----------{}:{}".format(k, v), end="\t")
二:编写装饰器,为函数加上统计时间的功能
deftiming(func):defwrapper(*args,**kwargs):
start = time.time()
result = func(*args,**kwargs)
stop = time.time()print("该程序执行的时间是------%s"%(stop - start))return result
return wrapper
三:编写装饰器,为函数加上认证的功能
deflogin(func):defwrapper1(*args,**kwargs):
user_dict ={}whileTrue:
user_name =input("请输入你的用户名:").strip()
user_psd =input("请输入你的密码:").strip()withopen(r"C:\Users\S\Desktop\userland.txt","rt", encoding="utf-8")as f:for line in f:
k, v = line.strip("\n").split(":")
user_dict[k]= v
if user_name in user_dict:if user_dict[user_name]== user_psd:print("欢迎{}".format(user_name))
result1 = func(*args,**kwargs)return result1
else:print("你输入的密码有误,请重新输入!")else:print("该用户名不存在。")return wrapper1
import time
user_dict ={}withopen(r"C:\Users\S\Desktop\userdata.txt","rt", encoding="utf-8")as f:for line in f:
k, v = line.strip("\n").split(":")
user_dict[k]= v
deflogin_4(func):defwrapper4(*args,**kwargs):whileTrue:# 记录输入开始时间
user_name =input("请输入你的用户名:").strip()
user_psd =input("请输入你的密码:").strip()if user_name in user_dict:if user_dict[user_name]== user_psd:global began
began = time.time()# 记录登录时间print("欢迎{}".format(user_name))global Tag # 声明全局变量
Tag =False# 修改recharge函数判断条件
result1 = func(*args,**kwargs)return result1
else:print("你输入的密码有误,请重新输入!")else:print("该用户名不存在。")return wrapper4
@login_4
defrecharge():while Tag:
user_name =input("请输入你的用户名:").strip()
user_psd =input("请输入你的密码:").strip()print(user_name)print(user_psd)
login_4(recharge)else:whileTrue:
time.sleep(1)print("正在执行充值功能.......")
end = time.time()if end > began+5:print("你未操作的时间过长,请重新登录!")
recharge()else:pass
声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
dic ={}defaddToDict(func):defwrapper8(*args,**kwargs):
i =1# 为字典添加索引whileTrue:# 判断索引是否存在if i in dic:
i +=1else:
dic[i]= func.__name__ # 将索引与变量名绑定
result8 = func()return result8
return wrapper8
@addToDict
defname():print("正在将name加入列表")
@addToDict
defweapon():print("正在将weapon加入列表")
@addToDict
defgender():print("正在将weapon加入列表")
name()
weapon()
gender()print(dic)
九 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
一:编写函数,(函数执行时间用time.sleep(n)代表)import timedef demo1(*args, **kwargs): time.sleep(0.2) for i in args: print("index1-----------{}".format(i), end="\t") print() for k, v in kwargs.items(): print("index2----------{}:{}".form