Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
a=0 b=1 class A: a=42 b=list((a,a+1,a+2)) x=A() print(x.b)
输出:[42,43,44]
VS
a=0 b=1 class A: a=42 b=list((a+i for i in range(3))) x=A() print(x.b)
输出:[0, 1, 2]
因此,在第一个示例中,使用了 a=42。但在第二个示例中,使用了 a=0。为什么呢?
好的,我在教授的幻灯片中找到了这个推理:
“类块中定义的名称范围仅限于类块;它不会扩展到方法的代码块——这包括理解和生成器表达式,因为它们是使用函数范围实现的。” - 赵一宝博士
所以在示例 2 中, list((a+i for i in range(3))) 是列表理解的一个示例。因此,它采用全局命名空间 a=0。它不能识别在类块 A() 中定义的 a=42。
希望有人可以审查我的推理,我不确定它是否完全正确。