我是python的新手,突然惊讶地发现变量在声明和分配的块外仍然可见。代码如下:
with open('data.txt', 'r') as file:
text = file.readlines()
# and when do I close the file?
for i in range(len(text)): # still can access the text even after the block.
print(text[i])
如何从块外部看到变量? 预先感谢。
答案 0 :(得分:1)
Python没有块作用域,它具有函数作用域以保持清晰度,但它不对函数进行任何作用域。
使用块隐式调用__enter__
和__exit__
方法,并在离开它们时将关闭文件,但是在这种情况下,您正在访问text
变量,该变量包含行列表不是文件。
如果未输入该块并且您引用了尚不存在的变量,则会发生此类代码的真正问题。
x = False
if x:
y = True
if y: # NameError: name 'y' is not defined
print ('yay')
与
x = False
y = False
if x:
y = True
if y: # all good
print ('yay')