with语句中变量的范围?

2024-04-24 13:32:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我仅使用以下方法从python中读取firstline

with open(file_path, 'r') as f:
    my_count = f.readline()
print(my_count)

我对变量的范围有点困惑。虽然打印工作很好,但最好先使用语句执行my_count = 0外部操作(例如在C中用于执行intmy_count = 0


Tags: path方法readlinemyascountwith语句
2条回答

你也应该通过PEP-343和Python Documentation。很明显,它不是关于创建范围,而是关于使用Context Manager。我引用了上下文管理器上的python文档

A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods.

Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.

with语句不创建作用域(如ifforwhile也不创建作用域)

因此,Python将分析代码,并看到您在with语句中进行了赋值,从而使变量成为局部变量(到实际范围)

在Python中,变量不需要初始化所有代码路径中:作为程序员,您有责任确保在使用变量之前对其进行赋值。这可能会导致代码更短:例如,您确信一个列表至少包含一个元素,然后您可以在for循环中赋值。在Java中,for循环中的赋值被认为是不安全的(因为循环体可能永远不会执行)

初始化之前with范围可以更安全,因为在with语句之后,我们可以安全地假设变量存在。另一方面,如果变量应该with语句中赋值,在with语句之前不初始化它实际上会导致额外的检查:如果在with语句中以某种方式跳过赋值,Python将出错

with语句仅用于上下文管理目的。它强制(通过语法)在缩进结束时关闭在with中打开的上下文

相关问题 更多 >