【发布时间】:2012-08-31 13:43:52
【问题描述】:
我有一个这样的单身
class Singleton:
class __impl:
def __init__(self):
print "INIT"
__instance = None
def __init__(self):
# Check whether we already have an instance
if Singleton.__instance is None:
Singleton.__instance = Singleton.__impl()
# Store instance reference as the only member in the handle
self.__dict__['_Singleton__instance'] = Singleton.__instance
def __getattr__(self, attr):
""" Delegate access to implementation """
return getattr(self.__instance, attr)
def __setattr__(self, attr, value):
""" Delegate access to implementation """
return setattr(self.__instance, attr, value)
当我创建了多个 Singleton 实例时,我收到了两次对 init 的调用,我的意思是“INIT”被打印了两次,我认为它不应该发生
有人知道这有什么问题或有更好的方法来实现吗??
【问题讨论】:
-
你知道
__new__()吗?您似乎正在做一些扭曲以便能够将此模式插入__init__()。 -
非常适合我...你能展示你用来测试它的代码吗?
-
我试过 new 但我不能,
-
代码太多,无法分享...
-
你有没有机会继承这个?