Decorator function:
1) add functionality
2) modify behavior
3) perform setup/teardown
4) diagnostic(timing)
----------------------------------------------
Original view :
def shout(wrapped):
def inner(*args, **kargs):
print('Before')
ret = wrapped(*args,**kargs)
print('After')
return ret
return inner
def myfunc():
print('Shoot him')
myshout = shout(myfunc)
myshout()
output :
Before
Shoot him
After
----------------------------------------------
def shout(wrapped):
def inner(*args, **kargs):
print('Before')
ret = wrapped(*args,**kargs)
print('After')
return ret
return inner
@shout
def myfunc():
print('Shoot him')
myfunc()
#++ output :# Before# Shoot him# After###################### but !! # Still it has a problem
# You can't get the right name !!myfunc.__name__ # Out[135]: 'inner'
---------------------------------------------
remedy for this !!
---------------------------------------------
from functools import wraps
def shout(wrapped):
@wraps(wrapped)
def inner(*args, **kargs):
print('Before')
ret = wrapped(*args,**kargs)
print('After')
return ret
return inner
@shout
def myfunc():
print('Shoot him')
myfunc()
output :
Before
Shoot him
After
#No more problem now !
myfunc.__name__ # Out[135]: 'myfunc'
---------------------------------------------
Usage (1) : counting !!
---------------------------------------------
def count(wrapped):
def inner(*args, **kwargs):
inner.counter += 1 return wrapped(*args, **kwargs)
inner.counter = 0 return inner
@count
def myfunc():
print('counting: ')
myfunc()
myfunc()
myfunc()
myfunc()
myfunc()
myfunc.counter # 5
---------------------------------------------
Usage (2) : timing
---------------------------------------------
import time
def timer(wrapped):
def inner(*args, **kwargs):
t = time.time()
for i in range(10000):
ret = wrapped(*args, **kwargs)
print(time.time() -t)
return inner
@timer
def myfunc():
# print('so simple!')
myfunc() # 0.2610
留言
張貼留言