python - 由缩进确定的 python 范围的目的是什么

标签 python

在 mac os-x 上的 python 2.7.5 中,我可以编写以下行。我的问题是变量 age1 是在一个内部 block 中声明的,因此在随后的外部 block 中不应该是可见的。但是 python 编译并且不会提示。如果我注释行 age1 = 25,则 python 会提示未声明变量 age1。

在 java/c++ 等其他语言中,在范围内声明的变量(由 {} 确定)在范围外不可见。所以我的问题是缩进确定的 python 范围的目的是什么。

age = 41
if age >= 41:
 print(">=41")
 age1 = 25 #this is declared inside the scope of print and should not be visible outside
if age1 == 25:
 print("==25")

最佳答案

从此excellent answer , Python 中只有四个作用域。

LEGB 规则。

L. Local. (Names assigned in any way within a function (def or lambda)), and not declared global in that function.

E. Enclosing function locals. (Name in the local scope of any and all enclosing functions (def or lambda), form inner to outer.

G. Global (module). Names assigned at the top-level of a module file, or declared global in a def within the file.

B. Built-in (Python). Names preassigned in the built-in names module : open,range,SyntaxError,...

如您所见,基于缩进/控制 block ,python 不会限制变量的可见性。

因此,如果该代码在一个函数内,那么该变量在创建后对该函数内代码的所有部分都是可见的。

如果该代码在模块中,则变量在创建后将对模块的所有部分可见。

当你试图访问一个变量时,首先会搜索局部作用域,如果没有找到则搜索闭包作用域,如果找不到则搜索模块作用域,如果找不到则搜索内置作用域,并且如果找不到,将抛出错误。

现在检查这个函数,

def func(x):
    if x == 0: y = 1
    print locals()

func(1)
func(0)

输出

{'x': 1}
{'y': 1, 'x': 0}

在第一种情况下,y 没有被创建,所以它不在本地范围内。但在第二种情况下,y 被添加到局部作用域,因此,它对共享局部作用域的所有代码都是可见的。

关于python - 由缩进确定的 python 范围的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20755132/

相关文章:

Python 一直显示 NameError : name 'name' is not defined

python - NGINX:将请求详细信息放在自定义 404.json 返回上

Python + Scipy : How to set the time frame for a spectrogram?

python - 在 Python 中声明一个数字。可能强调千?

python - 在 shell 中创建多对多关系

python - 如何从python中的N个不同正态分布中采样M次?在处理时间方面有没有 "faster"方式?

Python 构造 - 解析可变数量的可变长度记录

java - 图像层和形状之间的碰撞检测

Python newb : What's preventing this function from printing?

python - 在元素中找不到标签值