<p>您可以查看Python字节码反汇编,以了解<code>for</code>-loop是如何在Python中实现的:</p>
<pre><code>>>> import dis
>>> dis.dis('for x in it: pass')
1 0 SETUP_LOOP 14 (to 17)
3 LOAD_NAME 0 (it)
6 GET_ITER
>> 7 FOR_ITER 6 (to 16)
10 STORE_NAME 1 (x)
13 JUMP_ABSOLUTE 7
>> 16 POP_BLOCK
>> 17 LOAD_CONST 0 (None)
20 RETURN_VALUE
</code></pre>
<p>即使不看源代码,我们也可以猜测<code>__iter__</code>是由<code>GET_ITER</code>操作码调用的,而<code>__next__</code>是在<code>FOR_ITER</code>中调用的。你知道吗</p>
<p>事实上,CPython的<a href="https://hg.python.org/cpython/file/4e8ac4173b3c/Python/ceval.c#l2646" rel="nofollow">Python/ceval.c</a>证实了这一点,例如<code>GET_ITER</code>调用<a href="https://docs.python.org/3/c-api/object.html#c.PyObject_GetIter" rel="nofollow">^{<cd7>}</a>,它等价于<code>iter(iterable)</code>可以调用<code>iterable.__iter__()</code>方法。你知道吗</p>
<hr/>
<blockquote>
<p>In the python folder, where can I see the code of other built-in methods (like len(), or int()?</p>
</blockquote>
<p>这些函数也用C语言实现(在CPython中)。你可以在<a href="https://hg.python.org/cpython/file/default" rel="nofollow">CPython source repository</a>中看到它们。你知道吗</p>
<p>内置方法来自在<a href="https://hg.python.org/cpython/file/1c51f1650c42/Python/bltinmodule.c#l1827" rel="nofollow">Python/bltinmodule.c e.g., ^{<cd11>}</a>调用<a href="https://docs.python.org/3/c-api/object.html#c.PyObject_Length" rel="nofollow">^{<cd12>}</a>中实现的<code>builtins</code>模块。你知道吗</p>
<p><code>int</code>是Python中整数的类。它是在<a href="https://hg.python.org/cpython/file/1c51f1650c42/Objects/longobject.c#l4340" rel="nofollow">Objects/longobject.c</a>(python3)中实现的。你知道吗</p>
<hr/>
<blockquote>
<p>Isn't the CPython code in the Python folder?</p>
</blockquote>
<p>否。Python安装文件夹不包含CPython的源代码。它可能包含标准库中的纯Python模块,例如<a href="https://github.com/python/cpython/blob/master/Lib/fractions.py" rel="nofollow">Lib/fractions.py</a>,除非它们是压缩的,或者只安装了<code>.pyc</code>、<code>.pyo</code>文件等编译模块。你知道吗</p>
<p>要获取完整的源代码,请运行:</p>
<pre><code>$ hg clone https://hg.python.org/cpython
</code></pre>
<p>其中<code>hg</code>是<a href="http://mercurial.selenic.com/" rel="nofollow">Mercurial executable</a>。你知道吗</p>
<p>作为练习,您可以找到其他<a href="https://wiki.python.org/moin/PythonImplementations" rel="nofollow">Python implementations</a>如Pypy、Jython定义<code>GET_ITER</code>、<code>FOR_ITER</code>、<code>len()</code>、<code>int()</code>的位置。你知道吗</p>