带参数的装饰器? [英] Decorators with parameters?
问题描述
我对装饰器转移变量 insurance_mode有疑问。我可以通过以下装饰器语句来做到这一点:
I have a problem with the transfer of variable 'insurance_mode' by the decorator. I would do it by the following decorator statement:
@execute_complete_reservation(True)
def test_booking_gta_object(self):
self.test_select_gta_object()
但不幸的是,该语句不起作用。也许有更好的方法来解决这个问题。
but unfortunately, this statement does not work. Perhaps maybe there is better way to solve this problem.
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
推荐答案
带参数的修饰符的语法有些不同-具有参数的装饰器应返回一个函数,该函数将接受一个函数并返回另一个函数。因此,它实际上应该返回一个普通的装饰器。有点混乱吧?我的意思是:
The syntax for decorators with arguments is a bit different - the decorator with arguments should return a function that will take a function and return another function. So it should really return a normal decorator. A bit confusing, right? What I mean is:
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 you can read more on the subject - it's also possible to implement this using callable objects and that is also explained there.
这篇关于带参数的装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!