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

看板Python作者 (ChaN)時間7年前 (2018/05/14 13:41), 編輯推噓0(005)
留言5則, 2人參與, 7年前最新討論串1/1
# -*- 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

05/14 16:44, 7年前 , 1F
你的需求和singleton感覺無關, 要讓function被call的行為
05/14 16:44, 1F

05/14 16:45, 7年前 , 2F
與被呼叫的第N次有關, 個人會選擇用decorator的做法去修飾
05/14 16:45, 2F

05/14 16:46, 7年前 , 3F
回到db的實作, 可能是做一個cache去儲存撈過的結果.
05/14 16:46, 3F

05/14 20:44, 7年前 , 4F
你可以定義一個空變數,存取資料庫前去判斷是否有值
05/14 20:44, 4F

05/14 20:45, 7年前 , 5F
就像樓樓上說的做一個 cache
05/14 20:45, 5F
文章代碼(AID): #1Q-I5kv9 (Python)
文章代碼(AID): #1Q-I5kv9 (Python)