Python3 nonlocal vs Global

Source: Internet
Author: User

Consider a python program like this:

x = 12

def func ():

x = 1

Func ()

Print (x)

Output is: x = 12

Because the x defined inside the function is considered to belong to the local scope only, in order to show that I am referring to the global x instead of the new definition of a local x,

You can use the Global keyword:

x = 12

def func ();

Global X

x = 1

Func ()

Print (x)

You can see that the output has become 1, which means that a global variable has been successfully modified inside the function.

Another scenario is the problem of nested local scopes:

def g ():

x = 12

Func ():

x = 1

Func ()

Print (x)

G ()

The result of this output is 12 because the x defined at the Func function call is also considered to belong to the local scope only, but the x defined in the function g () is not a global variable, and the global keyword mentioned above is certainly not possible,

So there is the nonlocal, so write:

def g ():

x = 12

Func ():

nonlocal x

x = 1

Func ()

Print (x)

G ()

At this point, the result of the output is our expected 1, nonlocal is to declare a variable to refer to an external scope (except the global scope) defined.

It is important to note that the above keywords are needed because we are trying to modify global variables or variables that are in an external scope, and if you redefine global variables or external scope variables inside local scopes, just read-only access (such as print out) is perfectly fine, see this example:

A = 12
def g ():
b = 11
def func ():
Print (a)
Print (b)
Func ()
Return
if __name__ = = ' __main__ ':
G ()

Python3 nonlocal vs Global

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.