【问题标题】:Accessing variables declared inside a WITH block outside of it - why does it work?访问在其外部的 WITH 块内声明的变量 - 为什么它有效?
【发布时间】:2019-12-30 21:14:35
【问题描述】:

我开始学习一些 Python 并发现了 with 块。

下面是我的代码:

def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    with open(WORDLIST_FILENAME, 'r') as inFile:
        line = inFile.readline()
        wlist = line.split()
        print("  ", len(wlist), "words loaded.")
    print(wlist[0])
    inFile.close()
    return wlist

我的理解是 inFile 变量只会在块内存在/有效。但是block之后的inFile.close()调用不会导致程序崩溃或者抛出异常吗?

类似地,wlist 是在块内声明的,但我在方法结束时返回 wlist 没有问题。

谁能帮助解释为什么它会这样工作?也许我对 with blocks 的理解是不正确的。

【问题讨论】:

标签: python python-3.x with-statement


【解决方案1】:

您可以在 with 块中读取变量,因为 with 语句不会为您的程序添加任何范围,它只是在调用您在其中引用的对象时使您的代码更清晰的语句。

这个:

with open('file.txt', 'r') as file:
    f = file.read()
print(f)

输出与:

file = open('file.txt', 'r') 
f = file.read()
file.close()

print(f)

所以主要的区别是让你的代码更干净

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 2012-08-27
    • 2016-08-10
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2018-01-06
    相关资源
    最近更新 更多