Python closure function losing outer variable access

前端 未结 3 1154
时光取名叫无心
时光取名叫无心 2021-02-19 07:36

I just learned python @ decorator, it\'s cool, but soon I found my modified code coming out weird problems.

def with_wrapper(param1):
    def dummy_wrapper(fn):
         


        
3条回答
  •  走了就别回头了
    2021-02-19 07:58

    Handy for temporary situations or exploratory code (but otherwise not good practice):

    If you're wanting to capture a variable from the outer scope in Python 2.x then using global is also an option (with the usual provisos).

    While the following will throw (assignment of outer1 within inner makes it local and hence unbounded in the if condition):

    def outer():
        outer1 = 1
        def inner():
            if outer1 == 1:
                outer1 = 2
                print('attempted to accessed outer %d' % outer1)
    

    This will not:

    def outer():
        global outer1
        outer1 = 1
        def inner():
            global outer1
            if outer1 == 1:
                outer1 = 2
                print('accessed outer %d' % outer1)
    

提交回复
热议问题