如何使用可选参数构建装饰器? [英] How to build a decorator with optional parameters?
本文介绍了如何使用可选参数构建装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想制作一个可以使用或不使用参数的装饰器:
这样的东西:
I would like to make a decorator which could be used with or without a parameter : Something like this :
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'
在我的代码中,仅使用带参数的decorator起作用:如何继续使两者都起作用(带有和不带有参数)?
In my code, only the use of decorator with parameter is working: How to proceed to have both working (with and without parameter)?
推荐答案
我找到了一个示例,您可以使用 @trace
或 @trace('msg1','msg2')
:不错!
I found an example, you can use @trace
or @trace('msg1','msg2')
: nice!
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
这篇关于如何使用可选参数构建装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文