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__()
中。 - Silas Raytraceback.print_stack()
在__impl.__init__
中打印堆栈,这应该会给你一些提示,为什么它被调用了两次。 - Winston Ewert