楼主:
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去储存捞过的结果.