一、无参
1.定义 timmer 函数
2.将函数 foo 当作timmer函数的参数传给func
3.定义wrapper 函数
4.返回 wrapper 函数的内存地址
5.此时的 foo 就是 wrapper 的内存地址,加上()之后就开始执行wrapper下的代码
6-10.在时间运行开始至结束这段时间内,中间需要打印输出 “foo” 后睡眠 2S,至输出完毕之后,得到一个停止的时间,并且输出打印出从运行开始到运行结束这段时间的时间戳
二、有参装饰器
current_user={"user":None} def auth(engine=""file): def deco(func): def wrapper(*args,**kwargs): if current_user["user"]: #用户已经登录 res=func(*args,**kwargs) return res name=input("username:").strip() pwd=input("password:").strip() if engine=="file": with open("file.txt","r",encoding=""utf-8) as f: for line in f: line=line.strip(" ").split(":") if name==line[0] and pwd==line[1]: print("login successful...") current_user["user"]=user #登录成功储存用户状态 res=func(*args,**kwargs) return res else: print("error") elif engine=="mysql": print("mysql") else: print("无效语法") return wrapper return deco @auth(engine="file") def foo(): pirnt("hlello") time.sleep(1) foo