装饰器函数初级
直接举例子说吧!
def test():
print('look look') #这是个普通函数
接下来就是个简单的装饰器 (其实装饰器的意义就是:给其它函数增加功能用的)
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’
装饰器其实就相当于一个特殊的函数
接下来就是函数装饰器参数的应用
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