python - 带参数的装饰器?

标签 python decorator

装饰器对变量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 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 - 带参数的装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5929107/

相关文章:

python - 如何使用给定的装饰器获取python类的所有方法

python - Pandas Python - 比较不同的日期范围并检查它们是否在同一时间段

python - 从 os.system() 命令运行 "piping"脚本

python - 玛雅人 + python : Move pivot to bottom of bounding box

python - 检查多个函数参数的优雅方法

python - 创建一个线程安全的装饰器类

python - 如何让 pydoc 命令在 Windows 7 cmd 中工作?

python - 根据另一列中的值将列添加到 Python pandas DataFrame

python - 装饰生成器

python - scala:具有可变长度参数的函数对象的特征?