如果我针对本地命名空间创建一个类,它究竟是如何工作的?例如:
>>> 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/