- 问题:
-
我有一个问题的转移变量’保险模式’,由装饰。我可以通过下面的decorator语句来实现:
@execute_complete_reservation(True)
def test_booking_gta_object(self):
self.test_select_gta_object()但不幸的是,这种说法行不通。也许有更好的方法来解决这个问题
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
- 答案:
-
带参数的decorators的语法有点不同-带参数的decorator应该返回一个函数,该函数将接受一个函数并返回另一个函数。所以它应该返回一个普通的装饰器。有点困惑,对吧?我的意思是:
def decorator_factory(argument):
def decorator(function):
def wrapper(*args, **kwargs):
funny_stuff()
something_with_argument(argument)
result = function(*args, **kwargs)
more_funny_stuff()
return result
return wrapper
return decorator在Here你可以阅读关于这个主题的更多信息-也可以使用可调用对象来实现这一点,这里也对此进行了解释