作者chan15 (ChaN)
看板Python
标题[问题] 请教函式中 singleton 的写法
时间Mon May 14 13:40:59 2018
# -*- 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://webptt.com/cn.aspx?n=bbs/Python/M.1526276462.A.E49.html
1F:→ Yshuan: 你的需求和singleton感觉无关, 要让function被call的行为 05/14 16:44
2F:→ Yshuan: 与被呼叫的第N次有关, 个人会选择用decorator的做法去修饰 05/14 16:45
3F:→ Yshuan: 回到db的实作, 可能是做一个cache去储存捞过的结果. 05/14 16:46
4F:→ subi: 你可以定义一个空变数,存取资料库前去判断是否有值 05/14 20:44
5F:→ subi: 就像楼楼上说的做一个 cache 05/14 20:45