Utk*_*pta 3 c++ python programming-languages python-3.x
在 python 中,我们有一个名为nonlocal. 它和staticC++中的一样吗?如果我们在python中有嵌套函数,而不是在内部函数内部使用nonlocal,我们不能在外部函数中声明变量吗?这样就真的了nonlocal。
说明:staticC++ 中使用的关键字如下:
#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++ 中的静态相同吗?
C++static变量实际上只是范围较窄的全局变量(即它们是跨函数调用存储的持久性全局上下文)。
Pythonnonlocal只是关于嵌套作用域解析;外部函数的调用之间没有全局持久性(但会跨越来自同一个外部函数调用的内部函数的多次调用)。
| 归档时间: | 
 | 
| 查看次数: | 243 次 | 
| 最近记录: |