首页 > 解决方案 > 块内的变量在块外是否仍然可见?

问题描述

我是 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])

这怎么可能从块外部看到变量?提前致谢。

标签: python

解决方案


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')

推荐阅读