我们的教授今天告诉我们,我们可以构建一个迭代器,例如
class IteratorExample:
def __init__(self, n):
pass
def __iter__(self):
return self
def __next__(self):
if cond:
pass
else:
raise StopIteration
当我们使用它时,如 (for i in iteratorExample) 所示,解释器将调用 __iter__(self) 和 __next__(self) 方法。我的问题是:
- 如果我打开 C:\Python 文件夹 - 在哪里可以看到调用这些方法的代码?
- 在 python 文件夹中,哪里可以看到其他内置方法(如 len() 或 int())的代码?
最佳答案
您可以查看 Python 字节码反汇编,了解 Python 中如何实现 for
循环:
>>> 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
即使不查看源代码,我们也可以猜测 __iter__
是由 GET_ITER
操作码调用的,而 __next__
是在 中调用的FOR_ITER
。
事实上,CPython 的 Python/ceval.c确认它,例如 GET_ITER
调用 PyObject_GetIter(iterable)
相当于可以调用 iterable.__iter__()
方法的 iter(iterable)
。
In the python folder, where can I see the code of other built-in methods (like len(), or int()?
这些函数也用 C 实现(在 CPython 中)。您可以在 CPython source repository 中看到它们.
内置方法来自 Python/bltinmodule.c e.g., len()
中实现的 builtins
模块来电 PyObject_Size()
.
int
是 Python 中整数的类。它在 Objects/longobject.c 中实现(Python 3)。
Isn't the CPython code in the Python folder?
没有。 Python安装文件夹不包含CPython的源代码。它可能包含来自标准库的纯Python模块,例如Lib/fractions.py除非它们被压缩或仅安装了编译的模块,例如 .pyc
、.pyo
文件。
要获取完整的源代码,请运行:
$ hg clone https://hg.python.org/cpython
其中hg
是Mercurial executable .
作为练习,您可以找到其他 Python implementations 的位置例如Pypy、Jython定义GET_ITER
、FOR_ITER
、len()
、int()
。
关于python - Python3解释器中方法和类的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27676633/