Python3 命名空间和作用域

Posted on 2021-09-09 16:05  小愉  阅读(71)  评论(0编辑  收藏  举报
 

若没有使用 global 或 nonlocal 关键字对局部变量进行声明,在局部作用域中,可以访问全局命名空间中的变量,不可对其进行赋值。

对于教程中的这个实例:

a = 10
def test():
    a = a + 1
    print(a)
test()

运行后如下:(提示出错)

Traceback (most recent call last):
  File "<input>", line 5, in <module>
  File "<input>", line 3, in test
UnboundLocalError: local variable 'a' referenced before assignment

若程序改为如下:

a = 10
def test():    
    b = a + 1    
    print(b)
test()

运行结果:(正常运行)

11

在函数 test() 中,可以读取全局命名空间中的 “a”,对应语句 “b=a+1”。

即在局部作用域中,可以访问全局命名空间中的变量。

若程序改为如下:

a = 10
def test():    
    b = a + 1    
    a=b    
    print(b)
test()

运行:(提示出错)

Traceback (most recent call last):
  File "<input>", line 6, in <module>
  File "<input>", line 3, in test
UnboundLocalError: local variable 'a' referenced before assignment

错误的原因在于语句 “a=b”,对 “a” 进行赋值是不可以的。

即在函数 test() 中,不可以直接对全局命名空间中的 “a” 进行赋值。

若程序改为如下:

a = 10
def test():
    global a
    b = a + 1    
    a=b
    print(b)
test() #输出b
print(a) #输出a

运行:(正常运行)

11
11

语句 “global a” 声明了 “a” 采用全局命名空间中的 “a”,这样便可在函数 test() 中,对全局命名空间中的 “a” 直接进行赋值了。

若没有使用 global 或 nonlocal 关键字对局部变量进行声明,在局部作用域中,可以访问全局命名空间中的变量,不可对其进行赋值。

若使用了 global 或 nonlocal 关键字对局部变量进行声明,在局部作用域中,可以访问全局命名空间中的变量,也可对其进行赋值。

故,在局部作用域中,若想使用外部命名空间中的变量,应使用 global 或 nonlocal 关键字进行声明。