Decorators with parameters?

前端 未结 13 1427
我在风中等你
我在风中等你 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:15

    def decorator(argument):
        def real_decorator(function):
            def wrapper(*args):
                for arg in args:
                    assert type(arg)==int,f'{arg} is not an interger'
                result = function(*args)
                result = result*argument
                return result
            return wrapper
        return real_decorator
    

    Usage of the decorator

    @decorator(2)
    def adder(*args):
        sum=0
        for i in args:
            sum+=i
        return sum
    

    Then the

    adder(2,3)
    

    produces

    10
    

    but

    adder('hi',3)
    

    produces

    ---------------------------------------------------------------------------
    AssertionError                            Traceback (most recent call last)
     in 
    ----> 1 adder('hi',3)
    
     in wrapper(*args)
          3         def wrapper(*args):
          4             for arg in args:
    ----> 5                 assert type(arg)==int,f'{arg} is not an interger'
          6             result = function(*args)
          7             result = result*argument
    
    AssertionError: hi is not an interger
    

提交回复
热议问题