python - Python 的类闭包是如何工作的?

标签 python closures bytecode

如果我针对本地命名空间创建一个类,它究竟是如何工作的?例如:

>>> def foo():
...     i = 1
...     class bar(object):
...             j = i
...     return bar
... 
>>> dis(foo)
  2           0 LOAD_CONST               1 (1)
              3 STORE_DEREF              0 (i)

  3           6 LOAD_CONST               2 ('bar')
              9 LOAD_GLOBAL              0 (object)
             12 BUILD_TUPLE              1
             15 LOAD_CLOSURE             0 (i)
             18 BUILD_TUPLE              1
             21 LOAD_CONST               3 (<code object bar at 0xb74f8800, file "<stdin>", line 3>)
             24 MAKE_CLOSURE             0
             27 CALL_FUNCTION            0
             30 BUILD_CLASS         
             31 STORE_FAST               0 (bar)

  5          34 LOAD_FAST                0 (bar)
             37 RETURN_VALUE        

我很好奇的特定行是这些:

             15 LOAD_CLOSURE             0 (i)
             18 BUILD_TUPLE              1
             21 LOAD_CONST               3 (<code object bar at 0xb74f8800, file "<stdin>", line 3>)
             24 MAKE_CLOSURE             0
             27 CALL_FUNCTION            0
             30 BUILD_CLASS

我想我最想知道的是正在创建然后调用什么功能?这个函数是闭包附加到类的地方,还是发生在其他地方?

最佳答案

整个类(class),即

j = i

是一个代码对象,它在偏移量 21 处加载,然后通过 CALL_FUNCTION 在偏移量 27 处调用。然后将调用的结果(本地 namespace )与类名和基一起使用来创建类。 BUILD_CLASS 采用三个参数,类似于 type(name, bases, dict)功能:

Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute; the bases tuple itemizes the base classes and becomes the bases attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the dict attribute.

还有一篇很详细的文章"Notes on the Python Class Statement"解释类创建的工作原理。

关于python - Python 的类闭包是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2192822/

相关文章:

python - 为什么返回自身的函数在 python 3 中最大递归

python - 类型错误 : Object of type 'int32' is not JSON serializable

ios - 以下swift代码是什么意思?

python opencv : How to use Kalman filter

javascript - 无法创建 javascript 闭包

rust - 具有包含异步 block 的闭包的异步方法无法推断适当的生存期

java - 为什么.class文件的常量池表中没有列出一维数组类型?

java - 为什么 (int)MethodHandle.invokeExact 缺少 checkcast-instruction?

c++ - 任何 C/C++ 到非本地字节码编译器/解释器?

python - 使用 OpenCV(或使用其他工具)检测网格节点