Python nonlocal关键字

本文介绍了Python中的nonlocal关键字,解释了如何使用nonlocal来在嵌套函数中修改外部变量,并通过示例对比了使用与不使用nonlocal的区别。nonlocal关键字可以避免变量作用域混乱,确保代码的清晰性和正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关键字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()

在这里插入图片描述
正常运行,更改对内嵌函数外也依然有效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值