在Python中,我们有一个关键字叫做
nonlocal
。和C++中的static
一样吗?如果我们在Python中有嵌套函数,而不是在内部函数中使用nonlocal
,我们不能只在外部函数中声明变量吗?这样就真的nonlocal
.
澄清:
static
C++ 中使用的关键字:
#include <iostream>
int foo () {
static int sVar = 5;
sVar++;
return sVar;
}
using namespace std;
int main () {
int iter = 0;
do {
cout << "Svar :" foo() << endl;
iter++;
} while (iter < 3);
}
通过迭代给出输出:
Svar :6
Svar :7
Svar :8
因此,变量
Svar
保留了它的值。
如果我们在Python中有嵌套函数,而不是在内部函数内部使用nonlocal,我们不能在外部函数中声明变量吗?
不。如果省略
nonlocal
,内部函数中的赋值将创建一个新的本地副本,忽略外部上下文中的声明。
def test1():
x = "Foo"
def test1_inner():
x = "Bar"
test1_inner()
return x
def test2():
x = "Foo"
def test2_inner():
nonlocal x
x = "Bar"
test2_inner()
return x
print(test1())
print(test2())
...发出:
Foo
Bar
它和C++中的static一样吗?
C++
static
变量实际上只是范围较窄的全局变量(即它们是跨函数调用存储的持久全局上下文)。
Python
nonlocal
只是关于嵌套作用域解析;外部函数的调用之间不存在全局持久性(但来自同一外部函数调用的内部函数的多次调用)。
我对 C++ 中的
static
的理解是它可以有多种含义。
我理解你所说的“C++ 中的
static
”是一个在调用之间维护状态的变量。 python 中最接近的是 global
变量。
nonlocal
将嵌套函数中的值的生命周期限制为封闭函数的生命周期。这是global
和local
之间的妥协。
如果您在内部函数中省略
nonlocal
,则那里的变量将具有与内部函数相同的作用域和生命周期。当然,除非您正在阅读而不是编写它,在这种情况下它将与封闭函数的范围匹配,但不能用于维护内部函数的任何状态。
“非本地”不是静态的。考虑下面的例子
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
def foo():
foo.counter += 1
print("Counter is", foo.counter)
outer()
foo.counter = 0
foo()
foo()
foo()
这段代码的输出是这样的 内部:非本地 外部:非本地 计数器为 1 计数器为2 计数器是 3
变量
foo.counter
相当于C++中的static关键字。我希望这有帮助。