作用
用函数修饰另外一个函数,扩展另外一个已存在函数的功能
装饰器不修改源代码不修改调用方式还能增加新功能
语法就是原函数之前加@ 在开发时,装饰器写在被装饰函数之上
import time
def info(func):
def time_h():
begin_time=time.time()
func()
print(time.time()-begin_time)
return time_h
@info
def download():
print("开始下载")
time.sleep(3)
print("success")
@info
def upload():
print("shangchuan")
time.sleep(2)
print("success")
download()
upload()
无参装饰器
import time
def rongkji(fun):
def ti(*args,**kwargs):
be=time.time()
a=fun(*args,**kwargs)
print(time.time()-be)
return a
return ti
@rongkji
def xiazai(file):
print(file)
time.sleep(2)
print("sad")
return True
@rongkji
def upload():
print("suu")
time.sleep(2)
print("asdaf")
print(xiazai("apple"))
有参装饰器
def outer(locatin):
def logger(func):
def warpper(*args,**kwargs):
if locatin == "cmd":
print("时间:%s,%s" % (time.time(), func.__name__))
elif locatin == "file":
with open("a.log", "a", encoding="utf-8") as f:
f.write("时间:%s,%s" % (time.time(), func.__name__))
else:
print("error")
return func(*args,**kwargs)
return warpper
return logger
@outer("cmd")
def testrun():
print("test run")
testrun()