Python nonlocal statement

前端 未结 9 1045
我在风中等你
我在风中等你 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:31

    help('nonlocal') The nonlocal statement


        nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*
    

    The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

    Names listed in a nonlocal statement, unlike to those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).

    Names listed in a nonlocal statement must not collide with pre- existing bindings in the local scope.

    See also:

    PEP 3104 - Access to Names in Outer Scopes
    The specification for the nonlocal statement.

    Related help topics: global, NAMESPACES

    Source: Python Language Reference

    0 讨论(0)
  • 2020-11-22 04:35
    a = 0    #1. global variable with respect to every function in program
    
    def f():
        a = 0          #2. nonlocal with respect to function g
        def g():
            nonlocal a
            a=a+1
            print("The value of 'a' using nonlocal is ", a)
        def h():
            global a               #3. using global variable
            a=a+5
            print("The value of a using global is ", a)
        def i():
            a = 0              #4. variable separated from all others
            print("The value of 'a' inside a function is ", a)
    
        g()
        h()
        i()
    print("The value of 'a' global before any function", a)
    f()
    print("The value of 'a' global after using function f ", a)
    
    0 讨论(0)
  • 2020-11-22 04:40

    In short, it lets you assign values to a variable in an outer (but non-global) scope. See PEP 3104 for all the gory details.

    0 讨论(0)
提交回复
热议问题