相关疑难解决方法(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万
查看次数

在另一个方法中计算python方法调用

我实际上是在尝试用Java做这个,但我正在自学python的过程中,这让我想知道是否有一个简单/聪明的方法用包装器或其他东西来做这件事.

我想知道在另一个方法中调用特定方法的次数.例如:

def foo(z):
    #do something
    return result

def bar(x,y):
    #complicated algorithm/logic involving foo
    return foobar
Run Code Online (Sandbox Code Playgroud)

所以对于每次使用各种参数调用bar,我想知道foo被调用了多少次,也许是这样的输出:

>>> print bar('xyz',3)
foo was called 15 times
[results here]
>>> print bar('stuv',6)
foo was called 23 times
[other results here]
Run Code Online (Sandbox Code Playgroud)

编辑:我意识到我可以在栏内打一个计数器并在我返回时将其转储,但如果有一些魔法可以用包装来完成同样的事情,那将会很酷.这也意味着我可以在其他地方重用相同的包装器,而无需修改方法中的任何代码.

python profiling

12
推荐指数
2
解决办法
9672
查看次数

标签 统计

python ×2

decorator ×1

profiling ×1