Why doesn't Python's nonlocal keyword like the global scope?

前端 未结 4 1305
一生所求
一生所求 2021-02-01 21:08

In Python 3.3.1, this works:

i = 76

def A():
    global i
    i += 10

print(i) # 76
A()
print(i) # 86

This also works:

def en         


        
4条回答
  •  情深已故
    2021-02-01 21:31

    The search order for names is LEGB, i.e Local, Enclosing, Global, Builtin. So the global scope is not an enclosing scope.

    EDIT

    From the docs:

    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.

提交回复
热议问题