朋友们,如需转载请标明出处:https://blog.csdn.net/jiangjunshow
声明:在人工智能技术教学期间,不少学生向我提一些python相关的问题,所以为了让同学们掌握更多扩展知识更好地理解AI技术,我让助理负责分享这套python系列教程,希望能帮到大家!由于这套python教程不是由我所写,所以不如我的AI技术教学风趣幽默,学起来比较枯燥;但它的知识点还是讲到位的了,也值得阅读!想要学习AI技术的同学可以点击跳转到我的教学网站。PS:看不懂本篇文章的同学请先看前面的文章,循序渐进每天学一点就不会觉得难了!
先看下面的代码:
>>>def tester(start): ... state = start ... def nested(label): ... print(label,state) ... return nested ... >>>F = tester(0) >>>F('spam') spam 0 >>>F('ham') ham 0
默认情况下,不允许修改嵌套的def作用域中的名称。所以下面的state += 1会报错:
>>>def tester(start): ... state = start ... def nested(label): ... print(label,state) ... state += 1 ... return nested ... >>>F = tester(0) >>>F('spam') UnboundLocalError: local variable 'state' referenced before assignment
如果我们在nested中把tester作用域中的state声明为一个nonlocal,我们就可以在nested函数中修改它了。即便我们通过名称F调用返回的nested函数时,tester已经返回并退出了,这也是有效的:
>>>def tester(start): ... state = start ... def nested(label): ... nonlocal state ... print(label,state) ... state += 1 ... return nested >>>F = tester(0) >>>F('spam') spam 0 >>>F('ham') ham 1 >>>F('eggs') eggs 2
通常使用嵌套作用域引用时,我们可以多次调用tester工厂函数,以便在内存中获得其状态的多个副本。每次调用都产生一个新的、独特的state对象,以至于更新一个函数的state不会影响到其他的。如下代码:
>>>G = tester(42) >>>G('spam') spam 42 >>>G('eggs') eggs 43 >>>F('bacon') bacon 3



