在 if 语句中初始化的变量的范围是什么? [英] What's the scope of a variable initialized in an if statement?

查看:29
本文介绍了在 if 语句中初始化的变量的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,所以这可能是一个简单的范围界定问题.Python 文件(模块)中的以下代码让我有点困惑:

I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly:

if __name__ == '__main__':
    x = 1

print x

在我使用过的其他语言中,这段代码会抛出异常,因为 x 变量是 if 语句的本地变量,不应存在于它之外.但是此代码执行并打印 1.谁能解释这种行为?在一个模块中创建的所有变量是否对整个模块全局/可用?

In other languages I've worked in, this code would throw an exception, as the x variable is local to the if statement and should not exist outside of it. But this code executes, and prints 1. Can anyone explain this behavior? Are all variables created in a module global/available to the entire module?

推荐答案

Python 变量的作用域是指派给它们的最里面的函数、类或模块.ifwhile 块之类的控制块不计算在内,因此在 if 内分配的变量仍然作用域为函数、类或模块.

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.

(由生成器表达式或列表/集合/字典推导式定义的隐式函数计数,就像 lambda 表达式一样.您不能将赋值语句填充到其中任何一个中,但 lambda 参数和for 子句目标是隐式赋值.)

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)

这篇关于在 if 语句中初始化的变量的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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