Python中nonlocal关键字

2022-01-21 0 366

在这篇文章中介绍了“Python的闭包与nonlocal”的用法,因为nonlocal是在Python3.0中新增的关键字,python2.x不提供支持,文中提出在Python2.x解决嵌套函数引用外部变量的方法只有使用global 关键字定义全局变量,另一种可行的解决方案是使用列表或字典代替要操作的关键字。

示例如下:

1.python3.0 使用nonlocal关键字

>>> def outer():
        x = 1
        def inner():
            nonlocal x
            x = 2
            print(\"inner:\", x)
        inner()
        print(\"outer:\", x)
 
 >>> outer()
 inner: 2
 outer: 2

2.python2.x  借助list或dict实现

>>> def outer():
        x = [1]
        def inner():
            x[0] += 1 #修改x[0]保存的值
            print(\"inner:\", x[0])
        inner()
        print(\"outer:\", x[0])
 >>> outer()
 inner: 2
 outer: 2

更多参考资料:

1.

2.javascript中作用域链定义与python作用域的异同

3.官方文档:

“The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

Names listed in a nonlocal statement, unlike to those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).

Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.“

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Python教程 Python中nonlocal关键字 https://www.20zxx.cn/294538/xuexijiaocheng/python.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务