Decorators with parameters?

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

    I presume your problem is passing arguments to your decorator. This is a little tricky and not straightforward.

    Here's an example of how to do this:

    class MyDec(object):
        def __init__(self,flag):
            self.flag = flag
        def __call__(self, original_func):
            decorator_self = self
            def wrappee( *args, **kwargs):
                print 'in decorator before wrapee with flag ',decorator_self.flag
                original_func(*args,**kwargs)
                print 'in decorator after wrapee with flag ',decorator_self.flag
            return wrappee
    
    @MyDec('foo de fa fa')
    def bar(a,b,c):
        print 'in bar',a,b,c
    
    bar('x','y','z')
    

    Prints:

    in decorator before wrapee with flag  foo de fa fa
    in bar x y z
    in decorator after wrapee with flag  foo de fa fa
    

    See Bruce Eckel's article for more details.

提交回复
热议问题