介紹@wraps decorator
沒加@wraps
<pre class='codeblock'>#!/usr/bin/python
import time
from functools import wraps
def timethis(func):
'''
Decorator that reports the excution time
'''
#@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end-start)
return result
return wrapper
@timethis
def countdown(n):
'''
Counts down
'''
while n > 0:
n -= 1
countdown(10000)
print countdown.__name__
print countdown.__doc__
<\pre>
結果:
'countdown', 0.00028896331787109375)wrapper
None
有加@wraps
結果:
('countdown', 0.00029587745666503906)countdown
Counts down
結論:
寫decorator若想保留原來的funcion __name__, __doc__那就要加 @wraps
否則就會被替換成 wrapper, None
否則就會被替換成 wrapper, None
沒有留言:
張貼留言