非本地与静态相同吗?

Is nonlocal same as static?

在 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 保留了它的价值。

我对 C++ 中 static 的理解是它可以有多种含义。

我理解你所说的“static 在 C++ 中”的意思是一个在调用之间保持状态的变量。 python 中最接近的是 global 变量。

nonlocal 将嵌套函数中值的生命周期限制为封闭函数的生命周期。它是 globallocal 之间的折衷。

如果您在内部函数中省略 nonlocal,则那里的变量将具有与内部函数相同的作用域和生命周期。当然,除非您正在阅读而不是编写它,在这种情况下它将匹配封闭函数的范围,但不会用于维护内部函数的任何状态。

"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关键字。希望对您有所帮助。

If we have nested functions in python, instead of using nonlocal inside inner function, can't we just declare the variable in the outer function?

没有。如果省略 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

Is it the same as static in C++?

C++ static 变量实际上只是范围较窄的全局变量(即它们是跨函数调用存储的持久全局上下文)。

Python nonlocal 只是关于嵌套范围解析;外部函数的调用之间没有全局持久性(但会跨同一个外部函数调用对内部函数的多次调用)。