python-使用'with'语句后的变量范围 [英] python - Variable scope after using a 'with' statement
问题描述
我在stackoverflow上找不到此问题的答案,所以我认为将其提出来可能有所帮助-
I didn't find the answer for this question on stackoverflow, so I thought it might be helpful to ask it, and have it here -
我打开文件后要声明新字典,方法如下:
I am declaring a new dictionary after I open a file, in the following way -
with open('some_file.txt','r') as f:
dict = json.loads(f.read()) #converts text to a dictionary
我的问题是-即使'with'范围结束后,我也能够达到dict的内容.
my question is - will I be able to reach dict content's even after the 'with' scope ends.
谢谢
推荐答案
是的,在Python中,文档:
Yes, in Python the scope of a variable ends only when the code block it's defined in ends, and the with
statement is not a code block per the documentation:
以下是块:模块,函数体和类定义.交互键入的每个命令都是一个块.脚本文件(作为标准输入提供给解释器或指定为解释程序的命令行参数)是一个代码块.剧本命令(在解释器命令行上用"-c"选项)是一个代码块.字符串参数传递给内置函数eval()和exec()是一个代码块.
The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the ‘-c’ option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block.
这篇关于python-使用'with'语句后的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!