nonlocal keyword in Python

高洛峰
Release: 2016-10-20 09:42:53
Original
2342 people have browsed it

This article introduces the usage of "Python's closure and nonlocal", because nonlocal is a new keyword in Python3.0 and python2.x does not provide support. The article proposes to solve nested functions in Python2.x The only way to reference external variables is to use the global keyword to define global variables. Another feasible solution is to use a list or dictionary instead of the keyword to be operated on.

Examples are as follows:

1.python3.0 using nonlocal keyword

>>> def outer():
        x = 1
        def inner():
            nonlocal x
            x = 2
            print("inner:", x)
        inner()
        print("outer:", x)
  
 >>> outer()
 inner: 2
 outer: 2
Copy after login

2.python2.x implemented with list or dict

>>> def outer():
        x = [1]
        def inner():
            x[0] += 1 #修改x[0]保存的值
            print("inner:", x[0])
        inner()
        print("outer:", x[0])
 >>> outer()
 inner: 2
 outer: 2
Copy after login


More references:

1. http://stackoverflow.com/questions/1261875/python-nonlocal-statement

2. Similarities and differences between scope chain definition in JavaScript and python scope

3.Official document:

“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."


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template