示例第一:
class Asdf(object):
def __enter__(self):
print("Enter")
return self
def __exit__(self, *args):
print("Exit")
def get_stuff(self):
return range(10)
class Moo(object):
with Asdf() as x:
a = x.get_stuff() # Works
b = ['asdf' for _ in range(3)] # Works
c = []
for _ in range(3):
c.append(x.get_stuff()) # Works
d = [x.get_stuff() for _ in range(3)] # NameError: name 'x' is not defined
m = Moo()
print(m.a)
print(m.b)
print(m.c)
print(m.d)
当我在Python 2.7.14中运行它时,我得到了预期的结果:
Enter
Exit
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
['asdf', 'asdf', 'asdf']
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
但是,当我使用Python 3.6.3运行它时,列表理解失败:
Enter
Exit
Traceback (most recent call last):
File "tmp.py", line 14, in <module>
class Moo(object):
File "tmp.py", line 25, in Moo
d = [x.get_stuff() for _ in range(3)] # NameError: name 'x' is not defined
File "tmp.py", line 25, in <listcomp>
d = [x.get_stuff() for _ in range(3)] # NameError: name 'x' is not defined
NameError: name 'x' is not defined
在Python 3中是否更改了列表推导的规则?为什么我不能在Python 3的列表推导中使用x
?