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

时间:2015-01-14 17:07:13

标签: python list-comprehension scoping dictionary-comprehension

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

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

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

  

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}

0 个答案:

没有答案
相关问题