装饰器
2018-05-11 本文已影响0人
噜噜迅儿
一个完整的decorator的写法如下:
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
@log ## now = log(now)
def now():
print('2015-3-25')
>>> now()
call now():
2015-3-25
或者针对带参数的decorator:
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log('execute') ## now = log('execute')(now)
def now():
print('2015-3-25')
>>> now()
execute now():
2015-3-25