栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python nonlocal关键字

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python nonlocal关键字

关键字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)
 in 
      7     print(x)
      8 
----> 9 test()

 in test()
      4         x += 1
      5         print(x)
----> 6     inner()
      7     print(x)
      8 

 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()


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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/529711.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号