python - 块内的变量在块外是否仍然可见?
问题描述
我是 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 没有块作用域,为了清晰起见它具有函数作用域,但它不强制函数内的任何作用域。
使用块隐式调用__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')
推荐阅读
- python-3.x - 在 tkinter 中接受 lambda 表达式作为用户的输入
- r - 为什么 drop_na(col) 和 filter(is.na(col)) 不同?
- bash - 一些迭代后,在循环中运行 aws 命令失败
- python - 计算Python中一维数组中最大点后每个(左右点)的距离
- jquery-mobile - JQuery外部工具栏不显示
- angular - 无法在角度单元测试中模拟服务并返回数据 - 未定义
- c# - CSharpScripting 安全性
- c# - 激活后如何禁用 AdaptiveSubmitAction 按钮?
- python - 我从串行收集数据的线程/计时器只运行一次
- c++ - 未定义模板 'std::__1::vector 的隐式实例化
- ' 错误