Primary function decorator

Examples of direct refused to speak!

the Test DEF (): 
Print ( 'look look') # This is a normal function
the next step is a simple decorator
import  time #调用时间模块
def show_time():

def inner(f):
start = time.time()
f()
time.sleep(3)
end = time.time()
print('spend %t'%(end - start))
return inner
@show_time() #等价于 test=show_time(test)
def test():
print('look look')
test() #结果 ‘look look’

Decorator in fact equivalent to a special function

The next step is the application function parameters decorator

import time
def logger(flag): #装饰器参数flag
def foo():
print('i love you')
def show_time(f):
def inner(*x,**y):
star = time.time()
f(*x,**y)
time.sleep(3)
end = time.time()
print('spend %s'%(end-star),'s')
if flag =='ture':
print('logger')
return inner
return show_time
@logger('ture') #foo = show_time(foo)
def foo(*a,**b):
num = 0
for i in a :
num +=i
print(num)
foo(3,4,7,86) #结果 100

Guess you like

Origin www.cnblogs.com/CIBud/p/11838736.html