Introduction
Decorator: essentially function, function is to add additional functionality to other function
principles:
1, does not modify the source code to be modified function
2, does not modify the modified function is called
Knowledge base decorator
decorator higher order function = + + nested closure function
Simple decorator
import time
#装饰器的架子
def timmer(func):# func = test
def wrapper():
#print(func)
start_time = time.time()
func()#就是在运行test()
stop_time = time.time()
print("运行时间就是%s" % (stop_time - start_time))
return wrapper
def test():
time.sleep(3)
print("test函数运行完毕")
test = timmer(test)#返回的是wrapper的地址
test()#执行的是wrapper()
Syntax pond
@timmer equivalent test = timmer (test)
import time
#装饰器的架子
def timmer(func):# func = test
def wrapper():
#print(func)
start_time = time.time()
func()#就是在运行test()
stop_time = time.time()
print("运行时间就是%s" % (stop_time - start_time))
return wrapper
@timmer
def test():
time.sleep(3)
print("test函数运行完毕")
#test = timmer(test)#返回的是wrapper的地址
test()#执行的是wrapper()