總網頁瀏覽量

【 Python學習 】裝飾器工廠 Decorator Factory

 # 計算1+2+3+...+max

def calFactory(max):
def calculate(cb):
def run():
result = 0
for n in range(max+1):
result += n
cb(result) #cb(result) 傳遞 resultshowing(result) 才能正確處理數值
return run
return calculate

@calFactory(10)
def showing(result):
print("加總結果為", result)
showing()
@calFactory(100) #需要加括號,否則會被當作裝飾器函式,而非裝飾器工廠
def showing(result):
print("加總結果為", result)
showing()

加總結果為 55
加總結果為 5050

沒有留言:

張貼留言

2026必勝客超值優惠代碼組合,享受美食就看這邊

94103四小福雙拼系列$199 13吋大比薩,雙拼-四小福+照燒雞 或 四小福+熱帶鳳梨海鮮總匯1個。 平日外帶限定-94199超值單點大比薩$199 13吋大比薩1個,7種超值口味-蒜香起司燻雞培根、義式培根黃金薯等任選。 平日外帶限定-94299人氣單點大比薩$299 13...