python - Python3解释器中方法和类的位置

标签 python interpreter language-implementation

我们的教授今天告诉我们,我们可以构建一个迭代器,例如

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) 方法。我的问题是:

  1. 如果我打开 C:\Python 文件夹 - 在哪里可以看到调用这些方法的代码?
  2. 在 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

其中hgMercurial executable .

作为练习,您可以找到其他 Python implementations 的位置例如Pypy、Jython定义GET_ITERFOR_ITERlen()int()

关于python - Python3解释器中方法和类的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27676633/

相关文章:

java - java中移位运算的实现

python - Matplotlib 中使用 RGB 值的颜色

python - Python3队列: When can a blocking wait with no timeout return None?

lua 解释器,必须导入文件两次才能获得全部功能

ocaml - 是否可以在 OCaml 解释器中使用箭头键?

docker - 通过 Ajax 使用 docker 执行沙箱命令

python - 信号获取多个Qcomboxs的多个内容作为函数中的多个参数

python - 检查 redis get key 是否可用,否则 python 脚本

interpreter - 在 Nimrod 中的 Brainfuck 翻译

ruby - 为什么 __FILE__ 是大写而 __dir__ 是小写?