<h2>与C代码类似</h2>
<p>你在想象你在python中的<code>for-loop</code>是这样的C代码:</p>
<pre><code>for (int i = 0; i < 10; i++)
if (i == 5)
i += 3;
</code></pre>
<p>更像是C代码:</p>
<pre><code>int r[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (int j = 0; j < sizeof(r)/sizeof(r[0]); j++) {
int i = r[j];
if (i == 5)
i += 3;
}
</code></pre>
<p>因此,在循环中修改<code>i</code>不会产生预期的效果。</p>
<h2>反汇编示例</h2>
<p>您可以查看<a href="http://docs.python.org/2/library/dis.html" rel="noreferrer">disassembly of the python code</a>来查看:</p>
<pre><code>>>> from dis import dis
>>> def foo():
... for i in range (0,10):
... if i==5:
... i+=3
... print i
...
>>> dis(foo)
2 0 SETUP_LOOP 53 (to 56)
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (0)
9 LOAD_CONST 2 (10)
12 CALL_FUNCTION 2
15 GET_ITER
>> 16 FOR_ITER 36 (to 55)
19 STORE_FAST 0 (i)
3 22 LOAD_FAST 0 (i)
25 LOAD_CONST 3 (5)
28 COMPARE_OP 2 (==)
31 POP_JUMP_IF_FALSE 47
4 34 LOAD_FAST 0 (i)
37 LOAD_CONST 4 (3)
40 INPLACE_ADD
41 STORE_FAST 0 (i)
44 JUMP_FORWARD 0 (to 47)
5 >> 47 LOAD_FAST 0 (i)
50 PRINT_ITEM
51 PRINT_NEWLINE
52 JUMP_ABSOLUTE 16
>> 55 POP_BLOCK
>> 56 LOAD_CONST 0 (None)
59 RETURN_VALUE
>>>
</code></pre>
<p>这一部分<a href="http://docs.python.org/2/library/dis.html#opcode-CALL_FUNCTION" rel="noreferrer">creates a range between 0 and 10</a>并实现了它:</p>
<pre><code> 3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (0)
9 LOAD_CONST 2 (10)
12 CALL_FUNCTION 2
</code></pre>
<p>此时,堆栈的顶部包含范围。</p>
<p>这个<a href="http://docs.python.org/2/library/dis.html#opcode-GET_ITER" rel="noreferrer">gets an iterator over the object on the top of the stack</a>,即范围:</p>
<pre><code> 15 GET_ITER
</code></pre>
<p>此时,堆栈的顶部包含一个已实现范围上的迭代器。</p>
<p><a href="http://docs.python.org/2/library/dis.html#opcode-FOR_ITER" rel="noreferrer">FOR_ITER begins iterating over the loop</a>使用位于堆栈顶部的迭代器:</p>
<pre><code> >> 16 FOR_ITER 36 (to 55)
</code></pre>
<p>此时,堆栈顶部包含迭代器的下一个值。</p>
<p>在这里你可以看到<a href="http://docs.python.org/2/library/dis.html#opcode-STORE_FAST" rel="noreferrer">the top of the stack is popped and assigned to ^{<cd2>}</a>:</p>
<pre><code> 19 STORE_FAST 0 (i)
</code></pre>
<p>因此无论您在循环中做什么,都将覆盖<code>i</code>。</p>
<p>这是一张<a href="http://en.wikipedia.org/wiki/Stack_machine" rel="noreferrer">overview of stack machines</a>如果你以前没看过的话。</p>