總網頁瀏覽量

【 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

沒有留言:

張貼留言

2025西安碑林海峽兩岸臨書徵件辦法

簡章 報名表 臨書目錄