Description of Pythonnonlocal and global keyword parsing

Source: Internet
Author: User
This article introduces Pythonnonlocal and global keyword parsing description nonlocal

First, we need to clarify that the nonlocal keyword is defined in the closure. See the following code:

x = 0def outer():    x = 1    def inner():        x = 2        print("inner:", x)    inner()    print("outer:", x)outer()print("global:", x)

Result

# inner: 2# outer: 1# global: 0

Now, add the nonlocal keyword to the closure for declaration:

x = 0def outer():    x = 1    def inner():        nonlocal x        x = 2        print("inner:", x)    inner()    print("outer:", x)outer()print("global:", x)

Result

# inner: 2# outer: 2# global: 0

Have you seen the difference? This is another nested function in a function. When nonlocal is used, the variable is declared not only in the inner () nested function.
It is effective in the entire Big function.

Global

Let's look at an example:

x = 0def outer():    x = 1    def inner():        global x        x = 2        print("inner:", x)    inner()    print("outer:", x)outer()print("global:", x)

Result

# inner: 2# outer: 1# global: 2

Global is used for variables in the entire environment, rather than for variables of function classes.

The above is the details of the explanation of Python nonlocal and global keywords. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.