在本例中,Python变量的作用域是封闭变量和局部变量之间的区别

2024-06-02 08:28:44 发布

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

我对python变量的范围感到困惑。这是怎么回事

考虑下面的例子

i = 12
if i==12 :
    str = "is equal"
else:
    str = "NOT"
print str  //Prints is equal - recognized the string str

变量str只在if语句的作用域中,它的作用域在else语句中丢失。因为python中没有提升。我对这个例子的工作原理感到困惑,我阅读了thispost,它指出变量的作用域按以下顺序排列

1-L (local variables are given preference)

2-E (Enclosing variables)

3-G (Global variables)

4-B (Builtin)

我的问题是封闭变量和局部变量有什么区别?你知道吗


Tags: thestringifisnotequal语句variables
2条回答

Python没有一般的块作用域,只有函数作用域(对于像class声明这样的情况还有一些额外的奇怪之处)。在函数中指定的任何名称在函数的生命周期内都将保持有效。你知道吗

嵌套函数声明时应用封闭范围,例如:

def foo(a):
    def bar(b):
        return a + b
    return bar

所以在本例中,foo(1)(2)将创建一个bar,它的封闭范围是一个带有a == 1foo调用,然后调用bar(2),它将a视为1。你知道吗

封闭作用域也适用于lambda函数;它们可以读取围绕使用lambda的点的作用域中可用的变量,因此对于这样的情况:

 val_to_key = {...}  # Some dictionary mapping values to sort key values
 mylist.sort(key=lambda x: val_to_key[x])

val_to_key是可用的;它不在sort函数的作用域中,但是lambda函数在声明时绑定封闭作用域,因此可以使用val_to_key。你知道吗

The variable str is only in the scope of if statement and its scope is lost at the else statement.

没有。Python是函数范围的,而不是块范围的。输入if块不会创建新的作用域,因此str变量仍在print的作用域中。你知道吗

封闭变量是来自封闭给定函数的函数的变量。它们发生在有闭包的情况下:

def f():
    x = 3
    def g():
        print x  # enclosing variable
    g()

相关问题 更多 >