1
wohenyingyu01 2015 年 6 月 8 日
下面呢?
|
2
nooper 2015 年 6 月 8 日
单例模式在多进程下呢?
|
3
est 2015 年 6 月 8 日
m = ModuleSingleton()
这货不就是全局变量? 多进程考虑单例模式,直接反问主考官星际网络30%掉包 1500ms 延迟下集群如何实现单例。 |
5
ibigbug 2015 年 6 月 8 日
ModuleSingleton 跟其他两个不一样吧。这个是事先生成好了一个放在那里等人来用。
|
6
binux 2015 年 6 月 8 日 第一次听说创建个全局变量就叫单例的。
如果这个单例我实际上不用呢?你也要创建吗? |
7
Smartype 2015 年 6 月 8 日 via iPhone
1. 这就是 singleton???
2. 这样就快? 哪位给解释下 |
8
mengzhuo OP |
9
hahastudio 2015 年 6 月 8 日
全局变量就算单例我也就不提了,用 Module 算是一个讨巧的方法
但是你只能庆幸你的 Python 实现是带 GIL 的,如果是不带 GIL 的= = |
10
dddd 2015 年 6 月 8 日 这是我们 Java 设计模式课上老师所讲的翻版: http://damnever.github.io/2015/04/07/singleton-pattern-in-python/
|
11
JQ 2015 年 6 月 8 日
以前都没有关注到这个
|
12
Smartype 2015 年 6 月 8 日
@dddd @hahastudio 对啊,double check才对嘛,我觉得楼主不知道我要说什么,好在python有GIL,也是可以的,哈哈
|
13
ming2281 2015 年 6 月 8 日
缓存一个URL在模块级别,题主是这样写的吗?
``` _URL = xxx def get(refresh=False): if refresh: get.reates = {} if get.retes: return get.rates with urllib.request.urlopen(_URL) as f: for line in f: line = line.rstrip().decode('utf-8') if not line or line.startswith(("#", "Date")): continue name, currency,*rest = re.split(r"\s*,\s*, line) key = "{}{})".format(name, currency) try: get.rates[key] = float(rest[-1]) except ValueError as err: print "error:{}: {}".format(err, line) return get.rates get.rates = {} ``` |
14
est 2015 年 6 月 9 日
还是ruby简单。直接 ||= 就行了。
|
15
aec4d 2015 年 8 月 6 日
题主啊,你应该先别谈效率。。。先写对了再说。。。
你这里至少要加一个@classmethod 这样就是一个正确的单例了。再根据6楼说的在调用的时候在创建。那么可以考虑这样写 class ModuleSingleton(object): @classmethod def get(cls): if not hasattr(cls, '_instance'): cls._instance = 0 cls._instance += 1 return cls._instance a = ModuleSingleton() |