Python'for'循环中的范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3611760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:56:31  来源:igfitidea点击:

Scoping in Python 'for' loops

pythonscope

提问by chimeracoder

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

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

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

The above will print (9,2).

以上将打印 (9,2)。

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.

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

采纳答案by Jeremy Brown

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 globalkeyword exists just for this reason (to signify that assignment is done at a global scope).

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

Update

更新

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

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

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.

之前将 for 循环变量设置为循环局部的提议偶然发现了现有代码依赖循环变量在退出循环后保持其值的问题,这似乎被认为是一个理想的特性。

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

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

回答by carl

A really useful case for this is when using enumerateand you want the total count in the end:

一个非常有用的情况是在使用时enumerate并且您最终想要总数:

for count, x in enumerate(someiterator, start=1):
    dosomething(count, x)
print "I did something {0} times".format(count)

Is this necessary? No. But, it sure is convenient.

这是必要的吗?不,但是,它确实很方便。

Another thing to be aware of: in Python 2, variables in list comprehensions are leaked as well:

另一件需要注意的事情:在 Python 2 中,列表推导式中的变量也会泄露:

>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> x
9

But, the same does not apply to Python 3.

但是,这不适用于 Python 3。

回答by atzz

Python does not have blocks, as do some other languages (such as C/C++ or Java). Therefore, scoping unit in Python is a function.

Python 没有块,其他一些语言(例如 C/C++ 或 Java)也没有块。因此,Python 中的作用域单元是一个函数。

回答by kindall

One of the primary influences for Python is ABC, a language developed in the Netherlands for teaching programming concepts to beginners. Python's creator, Guido van Rossum, worked on ABC for several years in the 1980s. I know almost nothing about ABC, but as it is intended for beginners, I suppose it must have a limited number of scopes, much like early BASICs.

对 Python 的主要影响之一是ABC,这是一种在荷兰开发的用于向初学者教授编程概念的语言。Python 的创造者 Guido van Rossum 在 1980 年代在 ABC 工作了几年。我对 ABC 几乎一无所知,但由于它是为初学者准备的,我想它的范围一定是有限的,就像早期的 BASIC 一样。

回答by Kirk Strauser

For starters, if variables were local to loops, those loops would be useless for most real-world programming.

首先,如果变量是循环的局部变量,那么这些循环对于大多数现实世界的编程将毫无用处。

In the current situation:

在目前的情况下:

# Sum the values 0..9
total = 0
for foo in xrange(10):
    total = total + foo
print total

yields 45. Now, consider how assignment works in Python. If loop variables were strictly local:

产量45。现在,考虑一下 Python 中的赋值是如何工作的。如果循环变量是严格局部的:

# Sum the values 0..9?
total = 0
for foo in xrange(10):
    # Create a new integer object with value "total + foo" and bind it to a new
    # loop-local variable named "total".
    total = total + foo
print total

yields 0, because totalinside the loop after the assignment is not the same variable as totaloutside the loop. This would not be optimal or expected behavior.

yields 0,因为total赋值后的循环内部与循环total外部的变量不同。这不是最佳或预期的行为。

回答by Mac

If you have a break statement in the loop (and want to use the iteration value later, perhaps to pick back up, index something, or give status), it saves you one line of code and one assignment, so there's a convenience.

如果您在循环中有一个 break 语句(并且想稍后使用迭代值,也许是为了获取、索引某些内容或给出状态),它会为您节省一行代码和一个赋值,因此很方便。