我创建了这样的代码片段来测试nonlocal
:
def main():
increased = 1
def try_stat():
nonlocal increased
unchanged = 1
unchanged += 1
increased += 1
print(f"unchanged = {unchanged} and increased = {increased}.")
for count in range(1, 4):
print(f"Here comes iteration {count}")
try_stat()
main()
运行它并获取:
$ python loc_stat.py
Here comes iteration 1
unchanged = 2 and increased = 2.
Here comes iteration 2
unchanged = 2 and increased = 3.
Here comes iteration 3
unchanged = 2 and increased = 4.
请注意,在声明非局部变量时,应处理两个步骤:
为什么不直接将语法设计为
def main():
# increased = 1
def try_stat():
nonlocal increased = 1
C使用带有块范围的静态设计来实现它
#include <stdio.h>
void try_stat(void);
int main(void)
{
for (int count = 1; count <=3; count++)
{
printf("Here comes iteration %d:\n", count);
try_stat();
}
return 0;
}
void try_stat(void)
{
int unchanged = 1;
static int increased = 1;
printf("unchanged = %d and increased = %d\n", ++unchanged, ++increased);
}
编译并随附
$ ./a.out
Here comes iteration 1:
unchanged = 2 and increased = 2
Here comes iteration 2:
unchanged = 2 and increased = 3
Here comes iteration 3:
unchanged = 2 and increased = 4
此解决方案似乎更直观,并且Cpython是用C编写的,
选择块范围内的当前非本地模式而不是C的本机静态的原因是什么?
答案 0 :(得分:1)
两者。 :-)
它们不是等效的。与nonlocal
变量不同,static
变量在此块之外可见。
实际上,我认为您要做的实际上是一个类成员变量。 C不是OO语言,static
变量用于封装两次调用之间的持久状态。 Python为此具有类和属性self
。