python – 带参数的装饰器?

我有装饰器传递变量’insurance_mode’的问题.我会通过以下装饰器声明来做到这一点:

 @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

解决方法:

你的意思是def test_booking_gta_object,对吗?无论如何,带参数的装饰器的语法有点不同 – 带参数的装饰器应该返回一个函数,该函数将接受一个函数并返回另一个函数.所以它应该真正返回一个普通的装饰器.有点混乱,对吧?我的意思是:

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你可以阅读更多关于这个主题 – 也可以使用可调用的对象来实现它,这也在那里解释.

上一篇:python – 调用Django模型保存/删除后调用函数


下一篇:在Python中获取方法参数名称