在python中,我们有一个名为nonlocal
的关键字。与C++中的^ {CD2}相同吗?如果我们在python中有嵌套函数,而不是在内部函数中使用非局部函数,那么我们不能在外部函数中声明变量吗?那样的话,它将是真正的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保留了它的价值
否。如果省略
nonlocal
,则内部函数中的赋值将创建一个新的本地副本,而忽略外部上下文中的声明。。。发射:
C++ +{{CD2>}变量实际上只是全局变量,范围较窄(即它们是跨函数调用存储的持久全局上下文)。p>
Python
nonlocal
只是关于嵌套范围解析;在外部函数调用之间没有全局持久性(但是在来自同一外部函数调用的内部函数的多个调用之间)“非局部”不是静态的。考虑下面的例子
此代码的输出如下所示 内部:非局部 外部:非本地 柜台是1号 柜台是2号 柜台是3号
变量^ {}是C++中的静态关键字的等价物。我希望这有帮助
我理解你所说的“
static
在C++中”是一个变量,它在调用之间保持状态。python中最接近的是global
变量nonlocal
将嵌套函数中的值的生存期限制为封闭函数的生存期。这是{如果要在内部函数中省略
nonlocal
,则该变量的作用域和生存期将与内部函数相同。当然,除非您是在读而不是在写,在这种情况下,它将匹配封闭函数的范围,但不用于维护内部函数的任何状态相关问题 更多 >
编程相关推荐