python系列教程192——为什么要使用nonlocal

Posted 人工智能AI技术

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python系列教程192——为什么要使用nonlocal相关的知识,希望对你有一定的参考价值。

朋友们,如需转载请标明出处:https://blog.csdn.net/jiangjunshow

声明:在人工智能技术教学期间,不少学生向我提一些python相关的问题,所以为了让同学们掌握更多扩展知识更好地理解AI技术,我让助理负责分享这套python系列教程,希望能帮到大家!由于这套python教程不是由我所写,所以不如我的AI技术教学风趣幽默,学起来比较枯燥;但它的知识点还是讲到位的了,也值得阅读!想要学习AI技术的同学可以点击跳转到我的教学网站。PS:看不懂本篇文章的同学请先看前面的文章,循序渐进每天学一点就不会觉得难了!

如下的代码允许在一个嵌套作用域中保持和修改状态:

def tester(start):

    state = start            # Each call gets its own state

    def nested(label):

        nonlocal state       # Remembers state in enclosing scope

        print(label,state)

        state += 1           # Allowed to change it if nonlocal

    return nested




F = tester(0)

F('spam')

上面这段代码只能在Python 3.0中工作。在Python 2.6中实现nonlocal效果的一种通常方法就是直接把状态移出到全局作用域:

>>>def tester(start):

...    global state           # Move it out to the module to change it

...    state = start          # global allows changes in module scope

...    def nested(label):

...        global state

...        print(label,state)

...        state += 1

...    return nested

...

>>>F = tester(0)

>>>F('spam')                  # Each call increments shared global state

spam 0

>>>F('eggs')

eggs 1

在这个例子中,这是有效的,但它需要在两个函数中都有global声明。更糟糕更为微妙的问题是,它只考虑到模块作用域中状态信息的单个共享副本——如果我们再次调用tester,将会重新设置模块的状态变量,以至于前面的调用的状态将被覆盖:

>>>G = tester(42)         # Resets state's singlecopy in global scope

>>>G('toast')

toast 42




>>>G('bacon')

bacon 43




>>>F('ham')               # Oops -- my counter has been overwritten!

ham 44

以上是关于python系列教程192——为什么要使用nonlocal的主要内容,如果未能解决你的问题,请参考以下文章

python系列教程192——为什么要使用nonlocal

超简单的Python教程系列——异步

超简单的Python教程系列——第14篇:异步

python系列教程132——为什么使用缩进语法

Python爬虫入门教程!全网最全反爬虫系列

Numerical Testing Reportes of A New Conjugate Gradient Projection Method for Convex Constrained Nonl