Decorators with parameters?

前端 未结 13 1406
我在风中等你
我在风中等你 2020-11-21 22:58

I have a problem with the transfer of variable \'insurance_mode\' by the decorator. I would do it by the following decorator statement:

@execute_complete_rese         


        
13条回答
  •  抹茶落季
    2020-11-21 23:17

    This is a template for a function decorator that does not require () if no parameters are to be given:

    import functools
    
    
    def decorator(x_or_func=None, *decorator_args, **decorator_kws):
        def _decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kws):
                if 'x_or_func' not in locals() \
                        or callable(x_or_func) \
                        or x_or_func is None:
                    x = ...  # <-- default `x` value
                else:
                    x = x_or_func
                return func(*args, **kws)
    
            return wrapper
    
        return _decorator(x_or_func) if callable(x_or_func) else _decorator
    

    an example of this is given below:

    def multiplying(factor_or_func=None):
        def _decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                if 'factor_or_func' not in locals() \
                        or callable(factor_or_func) \
                        or factor_or_func is None:
                    factor = 1
                else:
                    factor = factor_or_func
                return factor * func(*args, **kwargs)
            return wrapper
        return _decorator(factor_or_func) if callable(factor_or_func) else _decorator
    
    
    @multiplying
    def summing(x): return sum(x)
    
    print(summing(range(10)))
    # 45
    
    
    @multiplying()
    def summing(x): return sum(x)
    
    print(summing(range(10)))
    # 45
    
    
    @multiplying(10)
    def summing(x): return sum(x)
    
    print(summing(range(10)))
    # 450
    

提交回复
热议问题