python系列教程192

79 阅读2分钟

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

声明:在人工智能技术教学期间,不少学生向我提一些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