相关疑难解决方法(0)

带参数的装饰器?

我有装饰器传递变量'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 decorator

361
推荐指数
11
解决办法
21万
查看次数

如何在装饰器中使用上下文管理器以及如何将在decorator中创建的对象传递给装饰函数

我有一个测试类,需要在最后进行一些清理.为了确保用户不会忘记这样做,我想在类中添加一个上下文管理器.我还有一个装饰器,我想在其中使用此上下文管理器来创建测试类的对象并将其传递给装饰函数.它甚至可能吗?

这就是我要做的事情:

class test:
    def __init__(self, name):
        self._name = name
        print "my name is {0}".format(name)

    def exit():
        print "exiting"

    @contextmanager
    def testcm(self):
        print "inside cm"
        try:
            yield self
        finally:
            self.exit()

    def randomtest(self, str):
        print "Inside random test {0}".format(str)


def decorate(name):
    def wrapper(testf):
        def testf_wrapper(test):
            with test(name).testcm() as testobj:
                return testf(testobj)
            return testf_wrapper
        return wrapper
    return decorate

@decorate("whatever")
def testf(testobj):
    testobj.randomtest("randomness")
Run Code Online (Sandbox Code Playgroud)

该函数testf接受测试类对象 - testobj并用它做事.之后,由于上下文管理器,testcm确保调用清理函数.

所以有两个问题:

  1. 我如何在装饰器中使用上下文管理器,从我所知的装饰器必须返回一个函数,但如果我返回该函数(如上面的代码),上下文管理器将如何调用清理?

  2. 如何将装饰器中创建的对象传递给装饰函数,如果我像上面的代码一样传递它,我将如何调用装饰函数?

python contextmanager python-decorators

3
推荐指数
1
解决办法
508
查看次数