来源: Python和Singleton模式
根据上面的答案初始化最upvoted评论被多次调用,如果新收益类实例。
所以,我检查这个:
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
print 'Singleton.__new__ called with class', cls
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class Cache(Singleton):
def __init__(self, size=100):
print 'I am called with size', size
class S(Singleton):
def __init__(self, param):
print 'I am S with param', param
c = Cache(20)
s = S(10)
结果:
Singleton.__new__ called with class <class '__main__.Cache'>
I am called with size 20
Singleton.__new__ called with class <class '__main__.S'>
I am S with param 10
显然,init不会叫一个类继承辛格尔顿不止一次。 已不便在Python改变处理这个在此期间(考虑的问题是在2008年提出),还是我在这里失去了不便?