Python'for'循环中的范围 [英] Scoping in Python 'for' loops

查看:84
本文介绍了Python'for'循环中的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是在问 Python 的范围规则;我大致了解范围在 Python for 循环中是如何工作的.我的问题是为什么以这种方式做出设计决策.例如(无双关语):

I'm not asking about Python's scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example (no pun intended):

for foo in xrange(10):
    bar = 2
print(foo, bar)

以上将打印 (9,2).

The above will print (9,2).

这让我觉得很奇怪:'foo' 实际上只是控制循环,而 'bar' 是在循环内定义的.我可以理解为什么 'bar' 可能需要在循环外访问(否则,for 循环的功能将非常有限).我不明白的是为什么在循环退出后控制变量必须保持在范围内.根据我的经验,它只会使全局命名空间变得混乱,并且更难追踪其他语言的解释器会发现的错误.

This strikes me as weird: 'foo' is really just controlling the loop, and 'bar' was defined inside the loop. I can understand why it might be necessary for 'bar' to be accessible outside the loop (otherwise, for loops would have very limited functionality). What I don't understand is why it is necessary for the control variable to remain in scope after the loop exits. In my experience, it simply clutters the global namespace and makes it harder to track down errors that would be caught by interpreters in other languages.

推荐答案

最可能的答案是它只是保持语法简单,不会成为采用的绊脚石,而且许多人很高兴不必消除歧义在循环构造中分配名称时名称所属的范围.变量不在范围内声明,它由赋值语句的位置隐含.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

这篇关于Python'for'循环中的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆