看板 Python 關於我們 聯絡資訊
# -*- 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 只跑一次撈取資料庫呢 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.124.224.43 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1526276462.A.E49.html
Yshuan: 你的需求和singleton感覺無關, 要讓function被call的行為 05/14 16:44
Yshuan: 與被呼叫的第N次有關, 個人會選擇用decorator的做法去修飾 05/14 16:45
Yshuan: 回到db的實作, 可能是做一個cache去儲存撈過的結果. 05/14 16:46
subi: 你可以定義一個空變數,存取資料庫前去判斷是否有值 05/14 20:44
subi: 就像樓樓上說的做一個 cache 05/14 20:45