Decorator: essentially a function
function :( other decorative function) is to add additional functionality to other function
principles: 1. Do not modify the source code to be decorated function
2. You can not modify the way calls are decorated function
to achieve decorator knowledge base:
1, i.e. the function "variable"
2. higher order functions:
a: to a function name as an argument passed to another function (not to be modified to add decorative features case where the function of the source code)
B: returns the value It contains the function name (not modify function is called)
3, + higher order function nested function = decorator
import time
def timer(func):
print("x1")
def deco(*args,**kwargs):
print("x2")
start_time = time.time()
back = func(*args,**kwargs)
stop_time = time.time()
print("The run time of func is %s " % (stop_time - start_time))
return back
return deco
@timer # test1 = timer(test1)
def test1():
time.sleep(1)
print("in the test1")
@timer #test2 = timer(test2)
def test2(name,age):
time.sleep(1)
print("in the test2 is %s and %s"%(name,age))
return "I "
test1()
#print(test2("Huan",22))
#print("\033[33;1m xxxxxx \033[0m")
Running process:
First declare the function timer, then after encountering @timer, it will function into the timer. Then execute print ( "x1"), and declared inside a function deco, but not executed, the return deco test1 = deco, wait until the call test1 (), in fact, call timer in the deco. Achieved without modifying the source code, the source code does not change the way calls.