python in the global scope and nonlocal

1. global

global keyword for using global variables or functions in other local scope. But if you do not modify global variables may not use the global keyword.

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

Export

Traceback (most recent call last):
  File "D:\Desktop\test.py", line 6, in <module>
    global_test()
  File "D:\Desktop\test.py", line 4, in global_test
    gcount+=1
UnboundLocalError: local variable 'gcount' referenced before assignment

The first line defines a global variable (global keyword may be omitted). In global_test program function because 如果内部函数有引用外部函数的同名变量或者全局变量,并且对这个变量有修改.那么python会认为它是一个局部变量,又因为函数中没有gcount的定义和赋值,所以报错.


If you want to modify the global variables in the local, local needs also first declare the global variable

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

Export

1
[Finished in 0.1s]

If you do not declare local global variables, and does not modify global variables. Global Variables can be used normally (reference only not be modified)

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

Output:

0
1
[Finished in 0.2s]

2. nonlocal

nonlocal keyword for the outer layer (non-global) variables in function or other scopes

count = 10    # 全局变量
def make_counter(): 
    count = 0   # 局部变量, counter()函数中修改的这个count
    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()

Export

1
2
3

The first call to make_countera function to modify the local variables count, each will modify call

3. Other examples enhance the understanding of the global and nonlocal

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()   # 该方法只定义了一个局部的spam, 并未对外边的spam修改
    print("After local assignmane:", spam)     # 因此此处输出的是test spam
    do_nonlocal()   # nonlocal申明了该函数中修改的是外层的spam
    print("After nonlocal assignment:",spam)   # 因此此处输出 nonlocal spam
    do_global()     # global 申明该函数修改的是全局变量
    print("After global assignment:",spam)     # 因此此处输出的依然是do_nonlocal函数修改后的spam
 
scope_test()
print("In global scope:",spam)   # 输出全局变量spam, 即do_global函数中的spam

Output:

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

global defined variables b, can only be referenced within the function do_global within a function add_b, if you want to modify in the do_global, b must be declared global inside a function in do_global, indicating that global variables are modified outside b

def add_b():
    global  b
    b = 42
    def do_global():
        global  b
        b = b + 10
        print(b)
    do_global()
    print(b)
add_b()

Export

52
52

def add_b():
    global  b
    b = 42
    def do_global():
        global  a
        a = b + 10
        print(b)
    do_global()
    print(a)
add_b()
print("a = %s , b = %s " %(a, b))

Export

42
52
a = 52 , b = 42

def add_b():
    b = 42
    def do_global():
        nonlocal  b
        b =  10
        print(b)
    do_global()
    print(b)
add_b()

Export

10
10

def add_b():
    #global  b
    b = 42
    def do_global():
        nonlocal  b
        b =  10
        print(b)
    do_global()
    print(b)
add_b()
print(" b = %s " % b)

Export

10
10
Traceback (most recent call last):
  File "D:\Desktop\test.py", line 11, in <module>
    print(" b = %s " % b)
NameError: name 'b' is not defined

Description: nonlocal suitable for topical function in the local function, local variables in the innermost layer is arranged locally available, but not global


def add_b():
    def do_global():
        nonlocal  b
        b =  10
        print(b)
    do_global()
add_b()

Export

File "D:\Desktop\test.py", line 5
    nonlocal  b
    ^
SyntaxError: no binding for nonlocal 'b' found

Note: nonlocal To bind a local variable. But does not require global


def add_b():
    def do_global():
        global  b
        b =  10
        print(b)
    do_global()
    print(b)
add_b()
b = b + 30
print(" b = %s " % b)

Export

10
10
b = 40

def add_b():
    def do_global():
        global  b
        b =  10
        print(b)
    do_global()
    b  = b + 20
    print(b)
add_b()
b = b + 30
print(" b = %s " % b)

Export

10
Traceback (most recent call last):
  File "D:\Desktop\test.py", line 9, in <module>
    add_b()
  File "D:\Desktop\test.py", line 7, in add_b
    b  = b + 20
UnboundLocalError: local variable 'b' referenced before assignment

4. Reference

python in the global scope and nonlocal

Published 33 original articles · won praise 1 · views 2602

Guess you like

Origin blog.csdn.net/orangerfun/article/details/104467158