Python nonlocal statement

前端 未结 9 1063
我在风中等你
我在风中等你 2020-11-22 03:52

What does the Python nonlocal statement do (in Python 3.0 and later)?

There\'s no documentation on the official Python website and help(\"nonloca

9条回答
  •  被撕碎了的回忆
    2020-11-22 04:14

    Quote from the Python 3 Reference:

    The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.

    As said in the reference, in case of several nested functions only variable in the nearest enclosing function is modified:

    def outer():
        def inner():
            def innermost():
                nonlocal x
                x = 3
    
            x = 2
            innermost()
            if x == 3: print('Inner x has been modified')
    
        x = 1
        inner()
        if x == 3: print('Outer x has been modified')
    
    x = 0
    outer()
    if x == 3: print('Global x has been modified')
    
    # Inner x has been modified
    

    The "nearest" variable can be several levels away:

    def outer():
        def inner():
            def innermost():
                nonlocal x
                x = 3
    
            innermost()
    
        x = 1
        inner()
        if x == 3: print('Outer x has been modified')
    
    x = 0
    outer()
    if x == 3: print('Global x has been modified')
    
    # Outer x has been modified
    

    But it cannot be a global variable:

    def outer():
        def inner():
            def innermost():
                nonlocal x
                x = 3
    
            innermost()
    
        inner()
    
    x = 0
    outer()
    if x == 3: print('Global x has been modified')
    
    # SyntaxError: no binding for nonlocal 'x' found
    

提交回复
热议问题