小编mob*_*ing的帖子

为什么这个python代码表现出奇怪的范围规则

我正在运行Python 2.7.8(Anaconda Distribution),这段代码失败了.这看起来像Python实现中的一个错误,但我错过了什么?

class C:
    x = {2 : 1}
    y = {w for w in x if x[w]==1}
Run Code Online (Sandbox Code Playgroud)

运行此代码会出现以下错误消息:

NameError:未定义全局名称"x"

错误信息对我来说似乎也是错误的.

请注意,以下两个非常相似的代码片段可以正常工作:

# this works fine:
class C:
    x = {2 : 1}
    y = [w for w in x if x[w]==1]


# this works fine too:
x = {2 : 1}
y = {w for w in x if x[w]==1}
Run Code Online (Sandbox Code Playgroud)

python list-comprehension scoping dictionary-comprehension

12
推荐指数
0
解决办法
145
查看次数