且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python'for'循环中的范围

更新时间:2022-06-15 03:21:35

最可能的答案是它只是保持语法简单,不会成为采用的绊脚石,而且许多人很高兴不必消除歧义在循环构造中分配名称时名称所属的范围.变量不在范围内声明,它由赋值语句的位置隐含.global 关键字就是为此而存在的原因(表示分配是在全局范围内完成的).

The likeliest answer is that it just keeps the grammar simple, hasn't been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct. Variables are not declared within a scope, it is implied by the location of assignment statements. The global keyword exists just for this reason (to signify that assignment is done at a global scope).

更新

这里有一个关于这个主题的很好的讨论:http:///mail.python.org/pipermail/python-ideas/2008-October/002109.html

Here's a good discussion on the topic: http://mail.python.org/pipermail/python-ideas/2008-October/002109.html

之前的 for-loop 建议循环局部变量有偶然发现存在的问题依赖于循环变量的代码退出后保持其价值循环,似乎这是被视为一个理想的功能.

Previous proposals to make for-loop variables local to the loop have stumbled on the problem of existing code that relies on the loop variable keeping its value after exiting the loop, and it seems that this is regarded as a desirable feature.

简而言之,你可以将其归咎于 Python 社区 :P

In short, you can probably blame it on the Python community :P