我有装饰器传递变量'insurance_mode'的问题.我会通过以下装饰器声明来做到这一点:
@execute_complete_reservation(True)
def test_booking_gta_object(self):
self.test_select_gta_object()
Run Code Online (Sandbox Code Playgroud)
但不幸的是,这种说法不起作用.也许有更好的方法可以解决这个问题.
def execute_complete_reservation(test_case,insurance_mode):
def inner_function(self,*args,**kwargs):
self.test_create_qsf_query()
test_case(self,*args,**kwargs)
self.test_select_room_option()
if insurance_mode:
self.test_accept_insurance_crosseling()
else:
self.test_decline_insurance_crosseling()
self.test_configure_pax_details()
self.test_configure_payer_details
return inner_function
Run Code Online (Sandbox Code Playgroud) 我想创建一个可以与参数一起使用的Python装饰器:
@redirect_output("somewhere.log")
def foo():
....
Run Code Online (Sandbox Code Playgroud)
或没有它们(例如,默认情况下将输出重定向到stderr):
@redirect_output
def foo():
....
Run Code Online (Sandbox Code Playgroud)
那可能吗?
请注意,我不是在寻找重定向输出问题的不同解决方案,它只是我想要实现的语法的一个示例.
我想制作一个可以使用或不使用参数的装饰器:这样的东西:
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'
Run Code Online (Sandbox Code Playgroud)
在我的代码中,只使用带参数的装饰器工作:如何继续工作(有和没有参数)?