【发布时间】:2019-07-14 06:46:59
【问题描述】:
考虑以下代码:
class A:
ID = 5
VALUES = ((4, "four"), (5, "five"))
MAP = {
t[0]: t[1] for t in VALUES if t[0] != ID
}
这很令人惊讶(对我来说),因为VALUES 符号被正确找到,但代码给出了错误“NameError: global name 'ID' is not defined”。
只有t[0]: t[1] for t in VALUES 有效。为什么?
【问题讨论】:
-
try t[0]: t[1] for t in VALUES if t[0] != A.ID refer this stackoverflow.com/questions/13037426/…
-
@Pradam:不,此时 A 不在范围内。
-
A此时不在范围内?
-
没有。 (试试吧!)。 123
标签: python-3.x scope python-3.7