为什么不允许访问在另一个理解表达式定义的类变量中的类变量?

时间:2018-08-21 10:11:55

标签: python python-3.x static-variables class-variables

请参阅下面的Python 3示例。这种语言更改/设计的直觉是什么?如何解决呢?

Python 3示例:

Python 3.6.5 (default, Apr 25 2018, 14:23:58)
[GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
...   a = 9
...   l1=[1,2]
...   l2 = [a+n for n in l1]
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in Foo
  File "<stdin>", line 4, in <listcomp>
NameError: name 'a' is not defined
>>>

Python 2示例:

>>> class Foo(object):
...   a = 9
...   l1=[1,2]
...   l2 = [a+n for n in l1]
...
>>>
>>> f = Foo()
>>> f.a
9
>>> f.l1
[1, 2]
>>> f.l2
[10, 11]
>>>

0 个答案:

没有答案