示例工程 06-functions-closures

06-functions-closures/04-nonlocal-counter/nonlocal_counter.py

python · 0.6 KB

"""演示闭包与 nonlocal 计数器。"""
 
from __future__ import annotations
 
from collections.abc import Callable
 
 
def make_counter(start: int = 0) -> tuple[Callable[..., int], Callable[[], int]]:
    """返回 (increment, get),共享同一个 count。"""
    count = start
 
    def increment(step: int = 1) -> int:
        nonlocal count
        count += step
        return count
 
    def get() -> int:
        return count
 
    return increment, get
 
 
def main() -> None:
    increment, get = make_counter(10)
    print(f"after +5: {increment(5)}")
    print(f"after +1: {increment()}")
    print(f"get: {get()}")
 
 
if __name__ == "__main__":
    main()