zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Python nonlocal关键字

2023-04-18 12:30:57 时间

关键字nonlocal用来在函数或者其他作用域中使用外层(非全局变量)。换句话说,nonlocal用来声明变量不处于当前的函数当中,需要解释器在包含这个函数的函数中寻找nonlocal声明的同名变量,找到后就可以使用这个对象对应的值在当前函数中进行操作。

它用来在部分情况下代替global关键字,防止滥用。

不使用nonlocal

def test():
    x = 0
    def inner():
        x += 1
        print(x)
    inner()
    print(x)

test()

运行会报以下错误:

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-5-2afcb73ef2c4> in <module>
      7     print(x)
      8 
----> 9 test()

<ipython-input-5-2afcb73ef2c4> in test()
      4         x += 1
      5         print(x)
----> 6     inner()
      7     print(x)
      8 

<ipython-input-5-2afcb73ef2c4> in inner()
      2     x = 0
      3     def inner():
----> 4         x += 1
      5         print(x)
      6     inner()

UnboundLocalError: local variable 'x' referenced before assignment

使用nonlocal

def test():
    x = 0
    def inner():
        nonlocal x
        x += 1
        print(x)
    inner()
    print(x)

test()

正常运行,更改对内嵌函数外也依然有效。