首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 閉包實作計數器:nonlocal 與列表封裝狀態

     編輯:更多程式設計知識

計數器需在多次呼叫間保持狀態。閉包捕獲外部變數實現「帶狀態的函數」。Python 2 用列表繞過賦值限制,Python 3 直接用 nonlocal。

Python 2 相容寫法 (列表)


def generate_counter():
    CNT = [0]
    def add_one():
        CNT[0] += 1
        return CNT[0]
    return add_one

counter = generate_counter()
print(counter())  # 1
print(counter())  # 2
print(counter())  # 3

Python 3 現代寫法 (nonlocal)


def generate_counter():
    count = 0
    def add_one():
        nonlocal count
        count += 1
        return count
    return add_one

進階:參數化計數器


def make_counter(start=0, step=1):
    count = start - step
    def inc():
        nonlocal count
        count += step
        return count
    return inc

c1 = make_counter()
c2 = make_counter(100, 5)
print([c1() for _ in range(3)])  # [1, 2, 3]
print([c2() for _ in range(3)])  # [105, 110, 115]

應用場景

  • 產生唯一 ID (不需執行緒安全)。
  • API 呼叫次數限流計數。
  • 遞迴深度追蹤。
  • 延遲初始化單例模式。

執行緒安全版 (需鎖)


import threading

def make_threadsafe_counter():
    count = 0
    lock = threading.Lock()
    def inc():
        nonlocal count
        with lock:
            count += 1
            return count
    return inc

閉包計數器簡潔優雅,是 Python 狀態封裝的經典範例。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved