简体   繁体   English

Python的类闭包如何工作?

[英]How do Python's class closures work?

If I make a class against a local namespace, how exactly does it work? 如果我针对本地命名空间创建一个类,它究竟是如何工作的? For instance: 例如:

>>> 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        

The particular lines I'm curious about are these: 我很好奇的特殊线路是:

             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

I suppose the biggest thing that I'm wondering is what function is being made and then called? 我想,我想知道的最重要的事情是什么功能正在制作然后被调用? And is this function where the closures are attached to the class, or does that happen elsewhere? 这个函数是闭包附加到类的函数,还是其他地方发生的?

The whole class body, ie 整个班级的身体,即

j = i

is a code object, which gets loaded at offset 21 and then invoked at offset 27 via CALL_FUNCTION . 是一个代码对象,它在偏移量21处加载,然后通过CALL_FUNCTION在偏移量27处调用。 The result of the invocation (the local namespace) is then used together with the class name and the bases to create the class. 然后,调用的结果(本地名称空间)与类名和基础一起使用以创建类。 BUILD_CLASS takes three arguments, similar to the type(name, bases, dict) function: 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; name字符串是类名,并成为name属性; 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. dict字典是包含类体定义的命名空间,并成为dict属性。

There's also a very detailed article "Notes on the Python Class Statement" explaining how class creation works. 还有一篇非常详细的文章“关于Python类声明的注释”,解释了类创建是如何工作的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM