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

有没有办法对执行多次的代码块计时?

给定一个函数,如:

do_something_big():
  do_1()
  do_2()
  do_3()
Run Code Online (Sandbox Code Playgroud)

这很容易得到它需要运行任何时间do_something_big()或单个实例do_1()。但假设我有:

for _ in range(100000):
  do_something_big()
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来获得 100,000do_1需要多长时间?这并不难 - 您只需为每个人计时并更新一些全局状态以跟踪总时间。但是是否已经构建了一个实用程序来为我抽象它?

python python-3.x

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

创建装饰器取决于 kwargs 参数作为参数

我有一个代码:

from functools import wraps

def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        print kwargs["name"] # Should display Dean Armada
        print 'Calling decorated function'
        return f(*args, **kwargs)
    return wrapper

@my_decorator(name="Dean Armada")
def example():
    """Docstring"""
    print 'Called example function'

example()
Run Code Online (Sandbox Code Playgroud)

我想要实现的是让我的装饰器依赖 kwargs 参数作为其所有参数。我上面的代码抛出此错误

my_decorator() got an unexpected keyword argument 'name'
Run Code Online (Sandbox Code Playgroud)

python python-decorators

2
推荐指数
1
解决办法
2159
查看次数

标签 统计

python ×3

decorator ×1

python-3.x ×1

python-decorators ×1