“with"内的变量范围陈述? [英] Scope of variable within "with" statement?

查看:61
本文介绍了“with"内的变量范围陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 :

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

我对变量 my_count 的范围有点困惑.尽管打印效果很好,但最好先在语句之外执行 my_count = 0 之类的操作(例如在 C 中用于执行 int my_count = 0)>

I am bit confused over scope of variable my_count. Although prints work fine, would it be better to do something like my_count = 0 outside with statement first (for eg in C in used to do int my_count = 0)

推荐答案

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

A with statement does not create a scope (like if, for and while do not create a scope either).

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

As a result, Python will analyze the code and see that you made an assignment in the with statement, and thus that will make the variable local (to the real scope).

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

In Python variables do not need initialization in all code paths: as a programmer, you are responsible to make sure that a variable is assigned before it is used. This can result in shorter code: say for instance you know for sure that a list contains at least one element, then you can assign in a for loop. In Java assignment in a for loop is not considered safe (since it is possible that the body of the loop is never executed).

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

Initialization before the with scope can be safer in the sense that after the with statement we can safely assume that the variable exists. If on the other hand the variable should be assigned in the with statement, not initializing it before the with statement actually results in an additional check: Python will error if somehow the assignment was skipped in the with statement.

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

A with statement is only used for context management purposes. It forces (by syntax) that the context you open in the with is closed at the end of the indentation.

这篇关于“with"内的变量范围陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆