How to inject variable into scope with a decorator?

前端 未结 11 2085
我寻月下人不归
我寻月下人不归 2020-12-04 17:31

[Disclaimer: there may be more pythonic ways of doing what I want to do, but I want to know how python\'s scoping works here]

I\'m trying to find a way to make a dec

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 17:52

    Assuming that in python functions are objects, you can do...

    #!/usr/bin/python3
    
    
    class DecorClass(object):
        def __init__(self, arg1, arg2):
            self.a1 = arg1
            self.a2 = arg2
    
        def __call__(self, function):
            def wrapped(*args):
                print('inside class decorator >>')
                print('class members: {0}, {1}'.format(self.a1, self.a2))
                print('wrapped function: {}'.format(args))
                function(*args, self.a1, self.a2)
            return wrapped
    
    
        @DecorClass(1, 2)
        def my_function(f1, f2, *args):
            print('inside decorated function >>')
            print('decorated function arguments: {0}, {1}'.format(f1, f2))
            print('decorator class args: {}'.format(args))
    
    
        if __name__ == '__main__':
            my_function(3, 4)
    

    and the result is:

    inside class decorator >>
    class members: 1, 2
    wrapped function: (3, 4)
    inside decorated function >>
    decorated function arguments: 3, 4
    decorator class args: (1, 2)
    

    more explanation here http://python-3-patterns-idioms-test.readthedocs.io/en/latest/PythonDecorators.html

提交回复
热议问题