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

查看:358
本文介绍了在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变量的作用域是最里面的函数,类,或他们被分配的模块。控制块如如果块不计数,所以在内分配的变量如果仍然限定为函数,类或模块。

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天全站免登陆