参见英文答案 > Making decorators with optional arguments 14个
我想制作一个可以使用或不使用参数的装饰器:
像这样的东西:
class d(object):
def __init__(self,msg='my default message'):
self.msg = msg
def __call__(self,fn):
def newfn():
print self.msg
return fn()
return newfn
@d('This is working')
def hello():
print 'hello world !'
@d
def too_bad():
print 'does not work'
在我的代码中,只使用带参数的装饰器工作:如何继续工作(有和没有参数)?
解决方法:
我找到了一个例子,你可以使用@trace或@trace(‘msg1′,’msg2’):太好了!
def trace(*args):
def _trace(func):
def wrapper(*args, **kwargs):
print enter_string
func(*args, **kwargs)
print exit_string
return wrapper
if len(args) == 1 and callable(args[0]):
# No arguments, this is the decorator
# Set default values for the arguments
enter_string = 'entering'
exit_string = 'exiting'
return _trace(args[0])
else:
# This is just returning the decorator
enter_string, exit_string = args
return _trace