Python作用域与带有循环变量的默认参数相比较

来源:互联网 发布:windows字体怎么设置 编辑:程序博客网 时间:2024/05/21 10:05

Python作用域与带有循环变量的默认参数相比较

如果lambda或者def在函数中定义,嵌套在一个循环之中,并且嵌套的函数引用了上一层作用域的变量,该变量被循环所改变,所有在这个循环中产生的函数将会有相同的值——在最后一次循环中完成时被引用变量的值。
If a lambda or def defined within a function is nested inside a loop, and the nested function references an enclosing scope variable that is changed by that loop, all functions generated within the loop will have the same value—the value the referenced variable had in the last loop iteration. In such cases, you must still use defaults to save the variable’s current value instead.
具体情况如下:
这里写图片描述
如果能弄清楚嵌套作用域(例如:在def 中 def) ,那么可以这样理解:
lambda表达式其实也可以理解为一个函数(不知这样描述是否准确),那么lambda的调用动作的运行是在def运行后发生的,lambda记住了在def中嵌套作用域中的i。由于是循环,所以在调用makeActions后,实际上lambda只记住了最后一次循环的值,也就是4.

注:本人在学习Python,之前学过Java,这些东西与Java中的内容出入很大,并且属于基础知识,如果是在学习Python时囫囵吞枣,那么将会遇到很多无法理解的东西,以及很多低级的错误。我还在学习中,如若上述内容有地方描述错误,望您指正!

原创粉丝点击