1. decorator
① the role of decorator: without changing the function, adding new features before and after the function
② use doctrine: Open Closed Principle (Open: Open for extension of time; closed: closed for modification)
2. syntactic sugar: @ decorative function
Library 3. This section addresses: time (import time)
print (time.tim ()) # get the current time
print (time.sleep (interval)) # s in the program to stop for a while to perform here when
Decorator fixed pattern:
Example:
import time
def timmer (f): # decorator function, f is a function to be decorated
def inner( ):
start = time.time()
K = f ()
end = time.time()
return right
return inner
@timmer # syntactic sugar, call the method decorator function func = timmer (func) -> inner
def func (): # function is decorative
time.sleep(0.1)
print ( 'blogger so cool!')
return 'unmatched'
Decorator function with parameters:
import time
def timmer (f): # decorator function
def inner(*args,**kwargs):
start = time.time()
ret = f(*args,**kwargs)
end = time.time()
return right
return inner
@timmer # syntactic sugar, call the method decorator function func = timmer (func) -> inner
def func (a, b): # decorated function
time.sleep(0.1)
print ( 'blogger so cool!')
return 'unmatched'
To be understood that the order of execution decorative function in the program:
Decorator advanced :( stop function call, and three function)
When there are multiple parameters, when 500 functions, how to stop calling function
import time
flage = True
def wrapper(flage):
def timmer(f):
def inner(*args,**kwargs):
if flage:
start =time.time()
ret = f(*args,**kwargs)
end = time.time()
print(end-start)
return right
else:
ret = f(*args,**kwargs)
print ( 'function here:')
return inner
return timmer
@wrapper (flage) # equivalent wrapper (flage) = timmer, the first execution wrapper (), and then call the function timmer
def func(a.c):
rtime.sleep(0.3)
print('11')
func(1,2)
A plurality of functions installed eleven function:
def wrapper1(f):#f =func
def inner1():
print('wrapper1 after om func')
K = f ()
print('wrapper1 after om func')
return inner1
def wrapper2(f): #f=inner1
def inner2():
print('wrapper2 after om func')
K = f ()
print('wrapper2 after om func')
return inner2
def wrapper3(f): #f =inenr2
def inner3():
print('wrapper3 after om func')
K = f ()
print('wrapper3 after om func')
return inner3
@wrapper3 #func =wrapper3(func)=wrappr3(func) = inner3
@wrapper2 #func =wrapper2(func)= wrapper2(inner1) = inner2
@wrapper1 #func = wrapper1(func)-->inner1
Order # using three decorators, perform closest to the decoration of the decorator
def func ():
print ( "Niubi ')
func() #-->inner3()-->inner2()-->inner1()
#application:
It can be used for recording the user's visit
Execution time calculation of this function