我问的不是Python的作用域规则;我大致了解Python for循环中的作用域是如何工作的。我的问题是为什么设计决策是以这种方式做出的。例如(不是双关语):
for foo in xrange(10):
bar = 2
print(foo, bar)
上面将输出(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.
一个非常有用的例子是当使用enumerate时,你想要最终的总计数:
for count, x in enumerate(someiterator, start=1):
dosomething(count, x)
print "I did something {0} times".format(count)
这有必要吗?不。但是,它确实很方便。
另一件需要注意的事情是:在Python 2中,列表推导式中的变量也会被泄露:
>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> x
9
但是,这并不适用于Python 3。
对于初学者来说,如果变量是循环的局部变量,那么这些循环对于大多数实际编程来说是无用的。
在当前情况下:
# Sum the values 0..9
total = 0
for foo in xrange(10):
total = total + foo
print total
收益率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
结果为0,因为赋值后循环内的total与循环外的total不是同一个变量。这不是最优的或预期的行为。