我最近正在单步调试 CPython 源代码,特别是查看 symbol table entry编译期间的一个类。
我遇到了 typedef struct _symtable_entry
的以下条目结构:
[-- other entries --]
unsigned ste_needs_class_closure : 1; /* for class scopes, true if a
closure over __class__
should be created */
[-- other entries --]
我真的看不懂,也找不到实际设置ste_needs_class_closure == 1
的python代码示例.在其他失败的尝试中,我尝试了以下方法:
class foo:
y = 30
def __init__(self):
self.x = 50
def foobar(self):
def barfoo():
print(self.x)
print(y)
return barfoo
但是即使它执行了,ste_needs_class_closure
的值执行期间是0
而不是 1
正如我所希望的那样。
实际改变这个值的函数是 drop_class_free
这没有多大帮助。不幸的是,它也没有任何赞美它的评论。
实际用在 analyze_block
评论如下:
/* Check if any local variables must be converted to cell variables */
我可以将其理解为一个概念,但找不到它发生的例子。
我试过搜索 the changelog for Python 3.4 , 该成员首次出现但未找到对其的引用的版本。
那么,谁能解释一下对__class__ 的闭包 是什么意思,即类的局部变量何时转换为单元变量?理想情况下,一个在执行期间实际使此行为可见的示例会很棒。
最佳答案
Github’s blame view for that line of code向我们展示它是在 this commit 中添加的, 其中引用 Issue #12370 : 防止类体干扰 __class__
闭包。
根据错误报告,此尝试修复的问题类型的示例是:
In Python 3 the following code prints
False
because the use ofsuper()
has caused the__class__
descriptor to be omitted from the class namespace. Remove the use ofsuper
and it printsTrue
.class X(object): def __init__(self): super().__init__() @property def __class__(self): return int print (isinstance(X(), int))
(请注意,此代码使用了 new super() 。)
关于补丁的功能,同样来自错误报告:
The patch basically causes the following class statement:
class C(A, B, metaclass=meta): def f(self): return __class__
To be compiled approximately like this:
def _outer_C(*__args__, **__kw__): class _inner_C(*__args__, **__kw__): def f(self): return __class__ __class__ = _inner_C return _inner_C C = _outer_C(A, B, metaclass=meta)
…尽管后来的一些讨论表明 __args__
和 __kw__
的处理可能在最终补丁中发生了变化。
关于python - 关闭 __class__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34563179/