46 lines
1019 B
Python
46 lines
1019 B
Python
import stdio
|
|
import t, c
|
|
|
|
|
|
# ============================================================
|
|
# 闭包 + nonlocal/global 测试
|
|
# ============================================================
|
|
|
|
# 全局变量
|
|
g_count: int = 0
|
|
|
|
|
|
# global 关键字测试:修改全局变量
|
|
def test_global() -> int:
|
|
global g_count
|
|
g_count = g_count + 1
|
|
return g_count
|
|
|
|
|
|
# nonlocal 关键字测试:嵌套函数修改外层局部变量
|
|
def make_counter() -> t.CPtr:
|
|
count: int = 0
|
|
|
|
# 内部函数(闭包)捕获 count
|
|
def counter() -> int:
|
|
nonlocal count
|
|
count = count + 1
|
|
return count
|
|
|
|
return counter
|
|
|
|
|
|
def closure_test() -> int:
|
|
# global 测试
|
|
stdio.printf("global: %d\n", test_global())
|
|
stdio.printf("global: %d\n", test_global())
|
|
stdio.printf("global: %d\n", test_global())
|
|
|
|
# nonlocal/闭包测试
|
|
f: t.CPtr = make_counter()
|
|
stdio.printf("closure: %d\n", f())
|
|
stdio.printf("closure: %d\n", f())
|
|
stdio.printf("closure: %d\n", f())
|
|
|
|
return 0
|