# 装饰器中添加参数

• 实现方式1：
``````import time
from functools import wraps
def timer_func(func,time_lag):
@wraps(func)
def wer(*args,**kwargs):
t1=time.time()
r=func(*args,**kwargs)
t2=time.time()
cost=t2-t1+time_lag
print('time cost %s'%cost)
return r
return wer

def func(n:int):
while n>0:
n=n-1
return n
a=timer_func(func,time_lag=10)
a(1000000)``````

• 实现方式2：
``````from functools import wraps
import time
def timer(time_lag):

def decorator(func):
@wraps(func)
def wer(*args, **kwargs):
t1 = time.time()
r = func(*args, **kwargs)
t2 = time.time()
cost = t2 - t1
res=cost+time_lag
print('time cost %s' % res)
return func(*args, **kwargs)#返回函数本身结果
return wer#返回内函数
return decorator#返回外函数

def func(n:int):
'''
this is a func test
:param n:
:return:
'''
while n>0:
n=n-1
return n

>>>a=timer(10)#返回外函数，#传入time_lag=10
>>>print(a)
<function timer.<locals>.decorator at 0x000002027D8E5E50>
>>>b=a(func)#返回内函数
>>>print(b)
<function func at 0x000002027D9434C0>
>>>c=b(999999)#调用内函数返回结果
>>>print(c)
time cost 10.069796323776245
0
``````

``````@timer(10)#传入time_lag=10
def func(n:int):

while n>0:
n=n-1
return n
>>>func(99999)
time cost 10.008002042770386

@timer(20)#传入time_lag=20
def func1(n:int):

while n>0:
n=n-1
return n
>>>func1(22222222)
time cost 21.447203874588013``````
• 创建一个带参数的日志装饰器

``````def logged(level,name=None,message=None):

def decorator(func):
logname=name if name else func.__module__
log=logging.getLogger(logname)
logmsg=message if message else func.__name__

@wraps(func)
def wraper(*args,**kwargs):
log.log(level,message)
return func(*args,**kwargs)
return wraper
return decorator

@logged(logging.DEBUG,'test_name')
def func(a):
return a+1``````
1 声望
2 粉丝
0 条评论