非局部与静态相同吗?

2024-09-29 23:21:18 发布

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

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


Tags: 函数声明returnfooincludestatic局部关键字
3条回答

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++ +{{CD2>}变量实际上只是全局变量,范围较窄(即它们是跨函数调用存储的持久全局上下文)。p>

Pythonnonlocal只是关于嵌套范围解析;在外部函数调用之间没有全局持久性(但是在来自同一外部函数调用的内部函数的多个调用之间)

“非局部”不是静态的。考虑下面的例子

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号

变量^ {}是C++中的静态关键字的等价物。我希望这有帮助

<>我在C++中对^ {CD1>}的理解是,它可以有多种含义。

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

nonlocal将嵌套函数中的值的生存期限制为封闭函数的生存期。这是{}和{}之间的折衷

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

相关问题 更多 >

    热门问题