[問題] 請教函式中 singleton 的寫法

作者: chan15 (ChaN)   2018-05-14 13:40:59
# -*- coding: utf-8 -*-
points = (1, 2, 3, 2, 1)
def get_points():
def get_data_from_db(name):
if name != 2:
return None
return 'from db'
for point in points:
if point == 1:
print(1)
elif get_data_from_db(point):
print(get_data_from_db(point))
else:
print(3)
if __name__ == '__main__':
get_points()
請教一下各位,這是一個陽春的範例,points 會是浮動的內容
當 ponit 等於 2 時 get_data_from_db 會從資料庫取資料
同一個 points 迴圈中,get_data_from_db 取到的內容其實是相同的
這段程式碼怎麼改寫成 singleton 讓 points 的迴圈執行 get_data_from_db 只跑一次撈取資料庫呢
作者: Yshuan (倚絃)   2018-05-14 16:44:00
你的需求和singleton感覺無關, 要讓function被call的行為與被呼叫的第N次有關, 個人會選擇用decorator的做法去修飾回到db的實作, 可能是做一個cache去儲存撈過的結果.
作者: subi (細雨綿綿細雨)   2018-05-14 20:44:00
你可以定義一個空變數,存取資料庫前去判斷是否有值就像樓樓上說的做一個 cache

Links booklink

Contact Us: admin [ a t ] ucptt.com