Python Global vs nonlocal (2)

Source: Internet
Author: User

The basic usage of these two keywords is outlined in the previous article:

Global is used for local modification or redefinition of globals

Nonlocal used to modify or redefine external variables (except global variables) in an internal scope

It's just a shallow way of understanding.

Note the characteristics of Python, the variables are mutable and immutable, for the mutable variable, in the internal scope of the changes can be done completely, do not need the above two keyword modification, such as the following program:

A = 12
Li = [1, 2, 3]
def g ():
b = 11
LI[2] = 4 #li变量在内部作用域内被修改了
def func ():
Print (a)
Print (b)
Func ()
Return
if __name__ = = ' __main__ ':
G ()
Print (LI)

But in doing so, the situation has changed:

A = 12

Li = [1, 2, 3]
def g ():
b = 11
Li = [1, 1, 1] #这时修改的是整个list, which is equivalent to a variable redefinition, so Li is considered local and does not affect global variables
def func ():
Print (a)
Print (b)
Func ()
Return
if __name__ = = ' __main__ ':
G ()
Print (LI)

In conjunction with Python's knowledge of memory management, we can understand that all operations within, nested scopes are possible, as long as the reallocation of variable memory is not involved (such as immutable variable assignment, mutable variable overall assignment). If you want to use the same name to point to another piece of memory, be particularly clear about whether the change is global or local

Python Global vs nonlocal (2)

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.