跳转至

变量作用域关键字

global

函数内声明使用全局变量(即使用全局命名空间)

1
2
3
4
5
6
def f():  
    x = 20  
    print(x)  

x = 30  
f()  # 20
1
2
3
4
5
6
7
def f():  
    global x
    x = 15
    print(x)  

x = 30  
f()  # 15

nonlocal

内层函数里声明使用外层函数的变量(即使用外层函数的命名空间)

1
2
3
4
5
6
7
8
9
def outer():  
    x = 20  
    def inner():  
        nonlocal x  
        x = 30  
        print(x)  
    inner()  

outer()  # 30