Detailed usage explanation of global and nonlocal in python

One, global

1. The global keyword is used to use global variables in functions or other local scopes. But if you don't modify the global variable, you can also not use the global keyword.

gcount = 0

def global_test():
    gcount+=1
    print (gcount)
global_test()

The above code will report an error: the first line defines the global variable, and the external function is referenced and modified in the internal function , then python will think it is a local variable, because the internal function does not define and assign its gcount, So an error was reported.

 

2. If you want to modify the global variable locally, declare the global variable locally

gcount = 0
 
def global_test():
    global  gcount
    gcount+=1
    print (gcount)
global_test()
 

The above output is: 1

 

3. If global variables are not declared locally and global variables are not modified, they can be used normally

gcount = 0
 
def global_test():
    print (gcount)
global_test()

The above output is: 0

 

 Two, nonlocal

1. The variable declared by nonlocal is not a local variable or a global variable, but a variable in an outer nested function

def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter
        
def make_counter_test():
  mc = make_counter()
  print(mc())
  print(mc())
  print(mc())
  
make_counter_test()

The above output is:

1

2

3

Three, mixed use

def scope_test():
    def do_local():
        spam = "local spam" #此函数定义了另外的一个spam字符串变量,并且生命周期只在此函数内。此处的spam和外层的spam是两个变量,如果写出spam = spam + “local spam” 会报错
    def do_nonlocal():
        nonlocal  spam        #使用外层的spam变量
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"
    spam = "test spam"
    do_local()
    print("After local assignmane:", spam)
    do_nonlocal()
    print("After nonlocal assignment:",spam)
    do_global()
    print("After global assignment:",spam)
 
scope_test()
print("In global scope:",spam)

The above output is:

After local assignmane: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

 

This article reference: https://www.cnblogs.com/yuzhanhong/p/9183161.html

Guess you like

Origin blog.csdn.net/Matrix_cc/article/details/105757172