装饰器参数

两个参数

import time

def showtime(f):
def inner(*x,**y):
start = time.time()
f(*x,**y)
end = time.time()
print(end - start)

return inner

@showtime #等价于foo = showtime(foo
def add(a,b):
print(a+b)
time.sleep(2)
add(2,3)

多个参数
import time

def showtime(f):
def inner(*x,**y):
start = time.time()
f(*x,**y)
end = time.time()
print(end - start)

return inner

@showtime #等价于foo = showtime(foo
def add(*a,**b):
sum = 0
for i in a:
sum+=i
print(sum)
time.sleep(2)

add(2,3,5,6,7)

装饰器参数
增加一个日志函数


import time

def logger(flag=''):
def showtime(f):
def inner(*x,**y):
start = time.time()
f(*x,**y)
end = time.time()
print(end - start)
if flag=='true':
print('日志记录')
return inner
return showtime

@logger('true') #等价于foo = showtime(foo
def add(*a,**b):
sum = 0
for i in a:
sum+=i
print(sum)
time.sleep(2)

add(2,3,5,6,7)

@logger()
def bar():
print('bar...........')
time.sleep(2)
bar()
 
posted @ 2017-11-23 17:05  无敌帅帅头  阅读(136)  评论(0编辑  收藏  举报